diff --git a/.github/workflows/pretter-lint.yml b/.github/workflows/pretter-lint.yml
index d10eb6e5a21d0..e4d2fb03c592c 100644
--- a/.github/workflows/pretter-lint.yml
+++ b/.github/workflows/pretter-lint.yml
@@ -1,8 +1,8 @@
name: prettier-linter
on:
- push: {}
- pull_request: {}
+ push: {}
+ pull_request: {}
jobs:
prettier:
diff --git a/lcci/10.11.Peaks and Valleys/README_EN.md b/lcci/10.11.Peaks and Valleys/README_EN.md
index 364c11b3a853a..f02231607335e 100644
--- a/lcci/10.11.Peaks and Valleys/README_EN.md
+++ b/lcci/10.11.Peaks and Valleys/README_EN.md
@@ -20,6 +20,12 @@
## Solutions
+**Solution 1: Sorting**
+
+We first sort the array, and then traverse the array and swap the elements at even indices with their next element.
+
+The time complexity is $O(n \times \log n),ドル and the space complexity is $O(\log n)$. Here, $n$ is the length of the array.
+
### **Python3**
diff --git a/lcci/16.01.Swap Numbers/README.md b/lcci/16.01.Swap Numbers/README.md
index 0af9830be41ea..0dd5cc45598d5 100644
--- a/lcci/16.01.Swap Numbers/README.md
+++ b/lcci/16.01.Swap Numbers/README.md
@@ -19,7 +19,25 @@
-异或运算。
+**方法一:位运算**
+
+我们可以使用异或运算 $\oplus$ 来实现两个数的交换。
+
+异或运算有以下三个性质。
+
+- 任何数和 0ドル$ 做异或运算,结果仍然是原来的数,即 $a \oplus 0=a$。
+- 任何数和其自身做异或运算,结果是 0ドル,ドル即 $a \oplus a=0$。
+- 异或运算满足交换律和结合律,即 $a \oplus b \oplus a=b \oplus a \oplus a=b \oplus (a \oplus a)=b \oplus 0=b$。
+
+因此,我们可以对 $numbers$ 中的两个数 $a$ 和 $b$ 进行如下操作:
+
+- $a=a \oplus b,ドル此时 $a$ 中存储了两个数的异或结果;
+- $b=a \oplus b,ドル此时 $b$ 中存储了原来 $a$ 的值;
+- $a=a \oplus b,ドル此时 $a$ 中存储了原来 $b$ 的值;
+
+这样,我们就可以实现在不使用临时变量的情况下对两个数进行交换。
+
+时间复杂度 $O(1),ドル空间复杂度 $O(1)$。
diff --git a/lcci/16.01.Swap Numbers/README_EN.md b/lcci/16.01.Swap Numbers/README_EN.md
index b099c0dbec463..bf8df6356de4b 100644
--- a/lcci/16.01.Swap Numbers/README_EN.md
+++ b/lcci/16.01.Swap Numbers/README_EN.md
@@ -24,6 +24,26 @@
## Solutions
+**Solution 1: Bitwise Operation**
+
+We can use the XOR operation $\oplus$ to implement the swap of two numbers.
+
+The XOR operation has the following three properties:
+
+- Any number XORed with 0ドル$ remains unchanged, i.e., $a \oplus 0=a$.
+- Any number XORed with itself results in 0ドル,ドル i.e., $a \oplus a=0$.
+- The XOR operation satisfies the commutative and associative laws, i.e., $a \oplus b \oplus a=b \oplus a \oplus a=b \oplus (a \oplus a)=b \oplus 0=b$.
+
+Therefore, we can perform the following operations on two numbers $a$ and $b$ in the array $numbers$:
+
+- $a=a \oplus b,ドル now $a$ stores the XOR result of the two numbers;
+- $b=a \oplus b,ドル now $b$ stores the original value of $a$;
+- $a=a \oplus b,ドル now $a$ stores the original value of $b$;
+
+In this way, we can swap two numbers without using a temporary variable.
+
+The time complexity is $O(1),ドル and the space complexity is $O(1)$.
+
### **Python3**
diff --git a/lcci/16.02.Words Frequency/README.md b/lcci/16.02.Words Frequency/README.md
index 8846f6f4910c7..b4113b6e2277e 100644
--- a/lcci/16.02.Words Frequency/README.md
+++ b/lcci/16.02.Words Frequency/README.md
@@ -5,6 +5,7 @@
## 题目描述
+
设计一个方法,找出任意指定单词在一本书中的出现频率。
你的实现应该支持如下操作:
@@ -33,9 +34,11 @@ wordsFrequency.get("pen"); //返回1
**方法一:哈希表**
-我们用哈希表 `cnt` 统计每个单词出现的次数,`get` 函数直接返回 `cnt[word]` 即可。
+我们用哈希表 $cnt$ 统计 $book$ 中每个单词出现的次数。
+
+调用 `get` 函数时,我们只需要返回 $cnt$ 中对应的单词的出现次数即可。
-初始化哈希表 `cnt` 的时间复杂度为 $O(n),ドル其中 $n$ 为 `book` 的长度。`get` 函数的时间复杂度为 $O(1)$。空间复杂度为 $O(n)$。
+时间复杂度方面,初始化哈希表 $cnt$ 的时间复杂度为 $O(n),ドル其中 $n$ 为 $book$ 的长度。`get` 函数的时间复杂度为 $O(1)$。空间复杂度为 $O(n)$。
@@ -194,7 +197,7 @@ class WordsFrequency {
```rust
use std::collections::HashMap;
struct WordsFrequency {
- counter: HashMap
+ cnt: HashMap
}
@@ -205,15 +208,15 @@ struct WordsFrequency {
impl WordsFrequency {
fn new(book: Vec) -> Self {
- let mut counter = HashMap::new();
+ let mut cnt = HashMap::new();
for word in book.into_iter() {
- *counter.entry(word).or_insert(0) += 1;
+ *cnt.entry(word).or_insert(0) += 1;
}
- Self { counter }
+ Self { cnt }
}
fn get(&self, word: String) -> i32 {
- *self.counter.get(&word).unwrap_or(&0)
+ *self.cnt.get(&word).unwrap_or(&0)
}
}
diff --git a/lcci/16.02.Words Frequency/README_EN.md b/lcci/16.02.Words Frequency/README_EN.md
index 64304840e0ec0..3aa9b2fe56581 100644
--- a/lcci/16.02.Words Frequency/README_EN.md
+++ b/lcci/16.02.Words Frequency/README_EN.md
@@ -42,6 +42,14 @@ wordsFrequency.get("pen"); //returns 1
## Solutions
+**Solution 1: Hash Table**
+
+We use a hash table $cnt$ to count the number of occurrences of each word in $book$.
+
+When calling the `get` function, we only need to return the number of occurrences of the corresponding word in $cnt$.
+
+In terms of time complexity, the time complexity of initializing the hash table $cnt$ is $O(n),ドル where $n$ is the length of $book$. The time complexity of the `get` function is $O(1)$. The space complexity is $O(n)$.
+
### **Python3**
@@ -195,7 +203,7 @@ class WordsFrequency {
```rust
use std::collections::HashMap;
struct WordsFrequency {
- counter: HashMap
+ cnt: HashMap
}
@@ -206,15 +214,15 @@ struct WordsFrequency {
impl WordsFrequency {
fn new(book: Vec) -> Self {
- let mut counter = HashMap::new();
+ let mut cnt = HashMap::new();
for word in book.into_iter() {
- *counter.entry(word).or_insert(0) += 1;
+ *cnt.entry(word).or_insert(0) += 1;
}
- Self { counter }
+ Self { cnt }
}
fn get(&self, word: String) -> i32 {
- *self.counter.get(&word).unwrap_or(&0)
+ *self.cnt.get(&word).unwrap_or(&0)
}
}
diff --git a/lcci/16.02.Words Frequency/Solution.py b/lcci/16.02.Words Frequency/Solution.py
index 68ed016d35bb9..f4fa1f1747c74 100644
--- a/lcci/16.02.Words Frequency/Solution.py
+++ b/lcci/16.02.Words Frequency/Solution.py
@@ -1,11 +1,11 @@
-class WordsFrequency:
- def __init__(self, book: List[str]):
- self.cnt = Counter(book)
-
- def get(self, word: str) -> int:
- return self.cnt[word]
-
-
-# Your WordsFrequency object will be instantiated and called as such:
-# obj = WordsFrequency(book)
-# param_1 = obj.get(word)
+class WordsFrequency:
+ def __init__(self, book: List[str]):
+ self.cnt = Counter(book)
+
+ def get(self, word: str) -> int:
+ return self.cnt[word]
+
+
+# Your WordsFrequency object will be instantiated and called as such:
+# obj = WordsFrequency(book)
+# param_1 = obj.get(word)
diff --git a/lcci/16.02.Words Frequency/Solution.rs b/lcci/16.02.Words Frequency/Solution.rs
index dcdb54165e80c..d19e54d4bfd52 100644
--- a/lcci/16.02.Words Frequency/Solution.rs
+++ b/lcci/16.02.Words Frequency/Solution.rs
@@ -1,30 +1,30 @@
-use std::collections::HashMap;
-struct WordsFrequency {
- counter: HashMap
-}
-
-
-/**
- * `&self` means the method takes an immutable reference.
- * If you need a mutable reference, change it to `&mut self` instead.
- */
-impl WordsFrequency {
-
- fn new(book: Vec) -> Self {
- let mut counter = HashMap::new();
- for word in book.into_iter() {
- *counter.entry(word).or_insert(0) += 1;
- }
- Self { counter }
- }
-
- fn get(&self, word: String) -> i32 {
- *self.counter.get(&word).unwrap_or(&0)
- }
-}
-
-/**
- * Your WordsFrequency object will be instantiated and called as such:
- * let obj = WordsFrequency::new(book);
- * let ret_1: i32 = obj.get(word);
+use std::collections::HashMap;
+struct WordsFrequency {
+ cnt: HashMap
+}
+
+
+/**
+ * `&self` means the method takes an immutable reference.
+ * If you need a mutable reference, change it to `&mut self` instead.
+ */
+impl WordsFrequency {
+
+ fn new(book: Vec) -> Self {
+ let mut cnt = HashMap::new();
+ for word in book.into_iter() {
+ *cnt.entry(word).or_insert(0) += 1;
+ }
+ Self { cnt }
+ }
+
+ fn get(&self, word: String) -> i32 {
+ *self.cnt.get(&word).unwrap_or(&0)
+ }
+}
+
+/**
+ * Your WordsFrequency object will be instantiated and called as such:
+ * let obj = WordsFrequency::new(book);
+ * let ret_1: i32 = obj.get(word);
*/
\ No newline at end of file
diff --git a/lcci/16.05.Factorial Zeros/README_EN.md b/lcci/16.05.Factorial Zeros/README_EN.md
index 471d49870eaf0..ed4a8574eede5 100644
--- a/lcci/16.05.Factorial Zeros/README_EN.md
+++ b/lcci/16.05.Factorial Zeros/README_EN.md
@@ -27,6 +27,19 @@
## Solutions
+**Solution 1: Mathematics**
+
+The problem is actually asking for the number of factors of 5ドル$ in $[1,n]$.
+
+Let's take 130ドル$ as an example:
+
+1. Divide 130ドル$ by 5ドル$ for the first time, and get 26ドル,ドル which means there are 26ドル$ numbers containing a factor of 5ドル$.
+2. Divide 26ドル$ by 5ドル$ for the second time, and get 5ドル,ドル which means there are 5ドル$ numbers containing a factor of 5ドル^2$.
+3. Divide 5ドル$ by 5ドル$ for the third time, and get 1ドル,ドル which means there is 1ドル$ number containing a factor of 5ドル^3$.
+4. Add up all the counts to get the total number of factors of 5ドル$ in $[1,n]$.
+
+The time complexity is $O(\log n),ドル and the space complexity is $O(1)$.
+
### **Python3**
diff --git a/lcci/16.07.Maximum/README_EN.md b/lcci/16.07.Maximum/README_EN.md
index 09fce68724d46..b27f482393d03 100644
--- a/lcci/16.07.Maximum/README_EN.md
+++ b/lcci/16.07.Maximum/README_EN.md
@@ -16,6 +16,14 @@
## Solutions
+**Solution 1: Bitwise Operation**
+
+We can extract the sign bit $k$ of $a-b$. If the sign bit is 1ドル,ドル it means $a \lt b$; if the sign bit is 0ドル,ドル it means $a \ge b$.
+
+Then the final result is $a \times (k \oplus 1) + b \times k$.
+
+The time complexity is $O(1),ドル and the space complexity is $O(1)$.
+
### **Python3**
diff --git a/lcci/16.11.Diving Board/README.md b/lcci/16.11.Diving Board/README.md
index 2af794e3f19e7..d3622ee13692b 100644
--- a/lcci/16.11.Diving Board/README.md
+++ b/lcci/16.11.Diving Board/README.md
@@ -5,6 +5,7 @@
## 题目描述
+
你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为shorter,长度较长的木板长度为longer。你必须正好使用k块木板。编写一个方法,生成跳水板所有可能的长度。
返回的长度需要从小到大排列。
示例:
@@ -24,6 +25,16 @@ k = 3
+**方法一:分类讨论**
+
+如果 $k=0,ドル则不存在任何一种方案,我们可以直接返回空列表。
+
+如果 $shorter=longer,ドル则我们只能使用长度为 $longer \times k$ 的木板,因此我们直接返回长度为 $longer \times k$ 的列表。
+
+否则,我们可以使用长度为 $shorter \times (k-i) + longer \times i$ 的木板,其中 0ドル \leq i \leq k$。我们在 $[0, k]$ 的范围内枚举 $i,ドル并计算对应的长度即可。对于不同的 $i,ドル我们不会得到相同的长度,这是因为,假如有 0ドル \leq i \lt j \leq k,ドル那么两者长度差为 $shorter \times (k-i) + longer \times i - shorter \times (k-j) - longer \times j,ドル整理得到长度差 $(i - j) \times (longer - shorter) \lt 0$。因此,对于不同的 $i,ドル我们会得到不同的长度。
+
+时间复杂度 $O(k),ドル其中 $k$ 为木板数量。忽略答案的空间消耗,空间复杂度 $O(1)$。
+
### **Python3**
diff --git a/lcci/16.11.Diving Board/README_EN.md b/lcci/16.11.Diving Board/README_EN.md
index 40525feff230f..697fc62500b68 100644
--- a/lcci/16.11.Diving Board/README_EN.md
+++ b/lcci/16.11.Diving Board/README_EN.md
@@ -33,6 +33,16 @@ k = 3
## Solutions
+**Solution 1: Case Analysis**
+
+If $k=0,ドル there is no solution, and we can directly return an empty list.
+
+If $shorter=longer,ドル we can only use a board with length $longer \times k,ドル so we directly return a list with length $longer \times k$.
+
+Otherwise, we can use a board with length $shorter \times (k-i) + longer \times i,ドル where 0ドル \leq i \leq k$. We enumerate $i$ in the range $[0, k],ドル and calculate the corresponding length. For different values of $i,ドル we will not get the same length, because if 0ドル \leq i \lt j \leq k,ドル then the difference in length is $(i - j) \times (longer - shorter) \lt 0$. Therefore, for different values of $i,ドル we will get different lengths.
+
+The time complexity is $O(k),ドル where $k$ is the number of boards. Ignoring the space consumption of the answer, the space complexity is $O(1)$.
+
### **Python3**
diff --git a/lcci/16.14.Best Line/README_EN.md b/lcci/16.14.Best Line/README_EN.md
index 180832f5108d9..43304d063f38e 100644
--- a/lcci/16.14.Best Line/README_EN.md
+++ b/lcci/16.14.Best Line/README_EN.md
@@ -24,6 +24,18 @@
## Solutions
+**Solution 1: Brute Force**
+
+We can enumerate any two points $(x_1, y_1), (x_2, y_2),ドル connect these two points into a line, and the number of points on this line is 2. Then we enumerate other points $(x_3, y_3),ドル and determine whether they are on the same line. If they are, the number of points on the line increases by 1; otherwise, the number of points on the line remains the same. Find the maximum number of points on a line, and the corresponding smallest two point indices are the answer.
+
+The time complexity is $O(n^3),ドル and the space complexity is $O(1)$. Here, $n$ is the length of the array `points`.
+
+**Solution 2: Enumeration + Hash Table**
+
+We can enumerate a point $(x_1, y_1),ドル store the slope of the line connecting $(x_1, y_1)$ and all other points $(x_2, y_2)$ in a hash table. Points with the same slope are on the same line, and the key of the hash table is the slope, and the value is the number of points on the line. Find the maximum value in the hash table, which is the answer. To avoid precision issues, we can reduce the slope $\frac{y_2 - y_1}{x_2 - x_1},ドル and the reduction method is to find the greatest common divisor, and then divide the numerator and denominator by the greatest common divisor. The resulting numerator and denominator are used as the key of the hash table.
+
+The time complexity is $O(n^2 \times \log m),ドル and the space complexity is $O(n)$. Here, $n$ and $m$ are the length of the array `points` and the maximum difference between all horizontal and vertical coordinates in the array `points`, respectively.
+
### **Python3**
diff --git a/lcci/16.15.Master Mind/README.md b/lcci/16.15.Master Mind/README.md
index a4e01468e07c8..c21a66eb3c2d0 100644
--- a/lcci/16.15.Master Mind/README.md
+++ b/lcci/16.15.Master Mind/README.md
@@ -25,7 +25,7 @@
**方法一:哈希表**
-同时遍历两个字符串,算出对应位置字符相同的个数,累加到 $x$ 中,然后将两个字符串出现的字符以及出现的次数分别记录在哈希表 `cnt1` 和 `cnt2` 中。
+同时遍历两个字符串,算出对应位置字符相同的个数,累加到 $x$ 中,然后将两个字符串出现的字符以及出现的次数分别记录在哈希表 $cnt1$ 和 $cnt2$ 中。
接着遍历两个哈希表,算出有多少共同出现的字符,累加到 $y$ 中。那么答案就是 $[x, y - x]$。
diff --git a/lcci/16.15.Master Mind/README_EN.md b/lcci/16.15.Master Mind/README_EN.md
index 4858bd680e80c..087dbdc746766 100644
--- a/lcci/16.15.Master Mind/README_EN.md
+++ b/lcci/16.15.Master Mind/README_EN.md
@@ -28,6 +28,14 @@
## Solutions
+**Solution 1: Hash Table**
+
+We simultaneously traverse both strings, count the number of corresponding characters that are the same, and accumulate them in $x$. Then we record the characters and their frequencies in both strings in hash tables $cnt1$ and $cnt2,ドル respectively.
+
+Next, we traverse both hash tables, count the number of common characters, and accumulate them in $y$. The answer is then $[x, y - x]$.
+
+The time complexity is $O(C),ドル and the space complexity is $O(C)$. Here, $C=4$ for this problem.
+
### **Python3**
diff --git a/lcci/16.16.Sub Sort/README_EN.md b/lcci/16.16.Sub Sort/README_EN.md
index 544a62ecd8bb4..692ad155908ec 100644
--- a/lcci/16.16.Sub Sort/README_EN.md
+++ b/lcci/16.16.Sub Sort/README_EN.md
@@ -21,6 +21,16 @@
## Solutions
+**Solution 1: Two Passes**
+
+We first traverse the array $array$ from left to right, and use $mx$ to record the maximum value encountered so far. If the current value $x$ is less than $mx,ドル it means that $x$ needs to be sorted, and we record the index $i$ of $x$ as $right$; otherwise, update $mx$.
+
+Similarly, we traverse the array $array$ from right to left, and use $mi$ to record the minimum value encountered so far. If the current value $x$ is greater than $mi,ドル it means that $x$ needs to be sorted, and we record the index $i$ of $x$ as $left$; otherwise, update $mi$.
+
+Finally, return $[left, right]$.
+
+The time complexity is $O(n),ドル where $n$ is the length of the array $array$. The space complexity is $O(1)$.
+
### **Python3**
diff --git a/lcci/16.17.Contiguous Sequence/README.md b/lcci/16.17.Contiguous Sequence/README.md
index 25730ea7b5aee..a93ea8c0b97fe 100644
--- a/lcci/16.17.Contiguous Sequence/README.md
+++ b/lcci/16.17.Contiguous Sequence/README.md
@@ -24,17 +24,19 @@
**方法一:动态规划**
-定义状态 `dp[i]` 表示以 `nums[i]` 结尾的连续子数组的最大和,初始时 `dp[0] = nums[0]`,当 $i\gt 0$ 时,状态转移方程为:
+我们定义 $f[i]$ 表示以 $nums[i]$ 结尾的连续子数组的最大和,那么状态转移方程为:
$$
-dp[i]=\max(dp[i-1],0)+nums[i], i>0
+f[i] = \max(f[i-1], 0) + nums[i]
$$
-答案为 `dp` 数组中的最大值。
+其中 $f[0] = nums[0]$。
-时间复杂度 $O(n),ドル其中 $n$ 表示 `nums` 的长度。
+答案为 $\max\limits_{i=0}^{n-1}f[i]$。
-由于 `dp[i]` 只与 `dp[i-1]` 有关,因此可以使用滚动数组优化空间复杂度,将空间复杂度降低到 $O(1)$。
+时间复杂度 $O(n),ドル空间复杂度 $O(n)$。其中 $n$ 为数组长度。
+
+我们注意到 $f[i]$ 只与 $f[i-1]$ 有关,所以我们可以用一个变量 $f$ 来表示 $f[i-1],ドル从而将空间复杂度降低到 $O(1)$。
@@ -45,21 +47,10 @@ $$
```python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
- n = len(nums)
- dp = [0] * n
- dp[0] = nums[0]
- for i in range(1, n):
- dp[i] = max(dp[i - 1], 0) + nums[i]
- return max(dp)
-```
-
-```python
-class Solution:
- def maxSubArray(self, nums: List[int]) -> int:
- ans = s = -inf
- for v in nums:
- s = max(s, 0) + v
- ans = max(ans, s)
+ ans = f = -inf
+ for x in nums:
+ f = max(f, 0) + x
+ ans = max(ans, f)
return ans
```
@@ -70,11 +61,10 @@ class Solution:
```java
class Solution {
public int maxSubArray(int[] nums) {
- int inf = Integer.MIN_VALUE;
- int ans = inf, s = inf;
- for (int v : nums) {
- s = Math.max(s, 0) + v;
- ans = Math.max(ans, s);
+ int ans = Integer.MIN_VALUE, f = Integer.MIN_VALUE;
+ for (int x : nums) {
+ f = Math.max(f, 0) + x;
+ ans = Math.max(ans, f);
}
return ans;
}
@@ -87,27 +77,10 @@ class Solution {
class Solution {
public:
int maxSubArray(vector& nums) {
- int n = nums.size();
- vector dp(n);
- dp[0] = nums[0];
- int ans = dp[0];
- for (int i = 1; i < n; ++i) { - dp[i] = max(dp[i - 1], 0) + nums[i]; - ans = max(ans, dp[i]); - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int maxSubArray(vector& nums) {
- int s = INT_MIN, ans = INT_MIN;
- for (int v : nums) {
- s = max(s, 0) + v;
- ans = max(ans, s);
+ int ans = INT_MIN, f = INT_MIN;
+ for (int x : nums) {
+ f = max(f, 0) + x;
+ ans = max(ans, f);
}
return ans;
}
@@ -118,13 +91,10 @@ public:
```go
func maxSubArray(nums []int) int {
- n := len(nums)
- dp := make([]int, n)
- dp[0] = nums[0]
- ans := dp[0]
- for i := 1; i < n; i++ { - dp[i] = max(dp[i-1], 0) + nums[i] - ans = max(ans, dp[i]) + ans, f := math.MinInt32, math.MinInt32 + for _, x := range nums { + f = max(f, 0) + x + ans = max(ans, f) } return ans } @@ -137,22 +107,16 @@ func max(a, b int) int { } ``` -```go -func maxSubArray(nums []int) int { - inf := math.MinInt32 - ans, s := inf, inf - for _, v := range nums { - s = max(s, 0) + v - ans = max(ans, s) - } - return ans -} +### **TypeScript** -func max(a, b int) int { - if a> b {
- return a
- }
- return b
+```ts
+function maxSubArray(nums: number[]): number {
+ let [ans, f] = [-Infinity, -Infinity];
+ for (const x of nums) {
+ f = Math.max(f, 0) + x;
+ ans = Math.max(ans, f);
+ }
+ return ans;
}
```
@@ -164,30 +128,10 @@ func max(a, b int) int {
* @return {number}
*/
var maxSubArray = function (nums) {
- const n = nums.length;
- const dp = new Array(n).fill(0);
- dp[0] = nums[0];
- let ans = dp[0];
- for (let i = 1; i < n; ++i) { - dp[i] = Math.max(dp[i - 1], 0) + nums[i]; - ans = Math.max(ans, dp[i]); - } - return ans; -}; -``` - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var maxSubArray = function (nums) { - const inf = -Infinity; - let s = inf; - let ans = inf; - for (const v of nums) { - s = Math.max(s, 0) + v; - ans = Math.max(ans, s); + let [ans, f] = [-Infinity, -Infinity]; + for (const x of nums) { + f = Math.max(f, 0) + x; + ans = Math.max(ans, f); } return ans; }; diff --git a/lcci/16.17.Contiguous Sequence/README_EN.md b/lcci/16.17.Contiguous Sequence/README_EN.md index 23b996e0bc31b..088364f8a8ce2 100644 --- a/lcci/16.17.Contiguous Sequence/README_EN.md +++ b/lcci/16.17.Contiguous Sequence/README_EN.md @@ -32,6 +32,22 @@ ## Solutions +**Solution 1: Dynamic Programming** + +We define $f[i]$ as the maximum sum of a continuous subarray that ends with $nums[i]$. The state transition equation is: + +$$ +f[i] = \max(f[i-1], 0) + nums[i] +$$ + +where $f[0] = nums[0]$. + +The answer is $\max\limits_{i=0}^{n-1}f[i]$. + +The time complexity is $O(n),ドル and the space complexity is $O(n)$. Here, $n$ is the length of the array. + +We notice that $f[i]$ only depends on $f[i-1],ドル so we can use a variable $f$ to represent $f[i-1],ドル thus reducing the space complexity to $O(1)$. + ### **Python3** @@ -39,21 +55,10 @@ ```python class Solution: def maxSubArray(self, nums: List[int]) -> int:
- n = len(nums)
- dp = [0] * n
- dp[0] = nums[0]
- for i in range(1, n):
- dp[i] = max(dp[i - 1], 0) + nums[i]
- return max(dp)
-```
-
-```python
-class Solution:
- def maxSubArray(self, nums: List[int]) -> int:
- ans = s = -inf
- for v in nums:
- s = max(s, 0) + v
- ans = max(ans, s)
+ ans = f = -inf
+ for x in nums:
+ f = max(f, 0) + x
+ ans = max(ans, f)
return ans
```
@@ -62,27 +67,10 @@ class Solution:
```java
class Solution {
public int maxSubArray(int[] nums) {
- int n = nums.length;
- int[] dp = new int[n];
- dp[0] = nums[0];
- int ans = dp[0];
- for (int i = 1; i < n; ++i) { - dp[i] = Math.max(dp[i - 1], 0) + nums[i]; - ans = Math.max(ans, dp[i]); - } - return ans; - } -} -``` - -```java -class Solution { - public int maxSubArray(int[] nums) { - int inf = Integer.MIN_VALUE; - int ans = inf, s = inf; - for (int v : nums) { - s = Math.max(s, 0) + v; - ans = Math.max(ans, s); + int ans = Integer.MIN_VALUE, f = Integer.MIN_VALUE; + for (int x : nums) { + f = Math.max(f, 0) + x; + ans = Math.max(ans, f); } return ans; } @@ -95,27 +83,10 @@ class Solution { class Solution { public: int maxSubArray(vector& nums) {
- int n = nums.size();
- vector dp(n);
- dp[0] = nums[0];
- int ans = dp[0];
- for (int i = 1; i < n; ++i) { - dp[i] = max(dp[i - 1], 0) + nums[i]; - ans = max(ans, dp[i]); - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int maxSubArray(vector& nums) {
- int s = INT_MIN, ans = INT_MIN;
- for (int v : nums) {
- s = max(s, 0) + v;
- ans = max(ans, s);
+ int ans = INT_MIN, f = INT_MIN;
+ for (int x : nums) {
+ f = max(f, 0) + x;
+ ans = max(ans, f);
}
return ans;
}
@@ -126,13 +97,10 @@ public:
```go
func maxSubArray(nums []int) int {
- n := len(nums)
- dp := make([]int, n)
- dp[0] = nums[0]
- ans := dp[0]
- for i := 1; i < n; i++ { - dp[i] = max(dp[i-1], 0) + nums[i] - ans = max(ans, dp[i]) + ans, f := math.MinInt32, math.MinInt32 + for _, x := range nums { + f = max(f, 0) + x + ans = max(ans, f) } return ans } @@ -145,22 +113,16 @@ func max(a, b int) int { } ``` -```go -func maxSubArray(nums []int) int { - inf := math.MinInt32 - ans, s := inf, inf - for _, v := range nums { - s = max(s, 0) + v - ans = max(ans, s) - } - return ans -} +### **TypeScript** -func max(a, b int) int { - if a> b {
- return a
- }
- return b
+```ts
+function maxSubArray(nums: number[]): number {
+ let [ans, f] = [-Infinity, -Infinity];
+ for (const x of nums) {
+ f = Math.max(f, 0) + x;
+ ans = Math.max(ans, f);
+ }
+ return ans;
}
```
@@ -172,30 +134,10 @@ func max(a, b int) int {
* @return {number}
*/
var maxSubArray = function (nums) {
- const n = nums.length;
- const dp = new Array(n).fill(0);
- dp[0] = nums[0];
- let ans = dp[0];
- for (let i = 1; i < n; ++i) { - dp[i] = Math.max(dp[i - 1], 0) + nums[i]; - ans = Math.max(ans, dp[i]); - } - return ans; -}; -``` - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var maxSubArray = function (nums) { - const inf = -Infinity; - let s = inf; - let ans = inf; - for (const v of nums) { - s = Math.max(s, 0) + v; - ans = Math.max(ans, s); + let [ans, f] = [-Infinity, -Infinity]; + for (const x of nums) { + f = Math.max(f, 0) + x; + ans = Math.max(ans, f); } return ans; }; diff --git a/lcci/16.17.Contiguous Sequence/Solution.cpp b/lcci/16.17.Contiguous Sequence/Solution.cpp index aa767a9df5eaa..65ddc133a9870 100644 --- a/lcci/16.17.Contiguous Sequence/Solution.cpp +++ b/lcci/16.17.Contiguous Sequence/Solution.cpp @@ -1,11 +1,11 @@ -class Solution { -public: - int maxSubArray(vector& nums) {
- int s = INT_MIN, ans = INT_MIN;
- for (int v : nums) {
- s = max(s, 0) + v;
- ans = max(ans, s);
- }
- return ans;
- }
+class Solution {
+public:
+ int maxSubArray(vector& nums) {
+ int ans = INT_MIN, f = INT_MIN;
+ for (int x : nums) {
+ f = max(f, 0) + x;
+ ans = max(ans, f);
+ }
+ return ans;
+ }
};
\ No newline at end of file
diff --git a/lcci/16.17.Contiguous Sequence/Solution.go b/lcci/16.17.Contiguous Sequence/Solution.go
index 7b272135e8061..1c0449096d3b8 100644
--- a/lcci/16.17.Contiguous Sequence/Solution.go
+++ b/lcci/16.17.Contiguous Sequence/Solution.go
@@ -1,9 +1,8 @@
func maxSubArray(nums []int) int {
- inf := math.MinInt32
- ans, s := inf, inf
- for _, v := range nums {
- s = max(s, 0) + v
- ans = max(ans, s)
+ ans, f := math.MinInt32, math.MinInt32
+ for _, x := range nums {
+ f = max(f, 0) + x
+ ans = max(ans, f)
}
return ans
}
diff --git a/lcci/16.17.Contiguous Sequence/Solution.java b/lcci/16.17.Contiguous Sequence/Solution.java
index e1e121511cbb4..c4ca0298d29ab 100644
--- a/lcci/16.17.Contiguous Sequence/Solution.java
+++ b/lcci/16.17.Contiguous Sequence/Solution.java
@@ -1,11 +1,10 @@
-class Solution {
- public int maxSubArray(int[] nums) {
- int inf = Integer.MIN_VALUE;
- int ans = inf, s = inf;
- for (int v : nums) {
- s = Math.max(s, 0) + v;
- ans = Math.max(ans, s);
- }
- return ans;
- }
+class Solution {
+ public int maxSubArray(int[] nums) {
+ int ans = Integer.MIN_VALUE, f = Integer.MIN_VALUE;
+ for (int x : nums) {
+ f = Math.max(f, 0) + x;
+ ans = Math.max(ans, f);
+ }
+ return ans;
+ }
}
\ No newline at end of file
diff --git a/lcci/16.17.Contiguous Sequence/Solution.js b/lcci/16.17.Contiguous Sequence/Solution.js
index 90fb51ee2308a..e81c9306bcee4 100644
--- a/lcci/16.17.Contiguous Sequence/Solution.js
+++ b/lcci/16.17.Contiguous Sequence/Solution.js
@@ -3,12 +3,10 @@
* @return {number}
*/
var maxSubArray = function (nums) {
- const inf = -Infinity;
- let s = inf;
- let ans = inf;
- for (const v of nums) {
- s = Math.max(s, 0) + v;
- ans = Math.max(ans, s);
+ let [ans, f] = [-Infinity, -Infinity];
+ for (const x of nums) {
+ f = Math.max(f, 0) + x;
+ ans = Math.max(ans, f);
}
return ans;
};
diff --git a/lcci/16.17.Contiguous Sequence/Solution.py b/lcci/16.17.Contiguous Sequence/Solution.py
index 89f3348b2afb6..2ac17f23e4ef0 100644
--- a/lcci/16.17.Contiguous Sequence/Solution.py
+++ b/lcci/16.17.Contiguous Sequence/Solution.py
@@ -1,7 +1,7 @@
-class Solution:
- def maxSubArray(self, nums: List[int]) -> int:
- ans = s = -inf
- for v in nums:
- s = max(s, 0) + v
- ans = max(ans, s)
- return ans
+class Solution:
+ def maxSubArray(self, nums: List[int]) -> int:
+ ans = f = -inf
+ for x in nums:
+ f = max(f, 0) + x
+ ans = max(ans, f)
+ return ans
diff --git a/lcci/16.17.Contiguous Sequence/Solution.ts b/lcci/16.17.Contiguous Sequence/Solution.ts
new file mode 100644
index 0000000000000..50dba9ee092e5
--- /dev/null
+++ b/lcci/16.17.Contiguous Sequence/Solution.ts
@@ -0,0 +1,8 @@
+function maxSubArray(nums: number[]): number {
+ let [ans, f] = [-Infinity, -Infinity];
+ for (const x of nums) {
+ f = Math.max(f, 0) + x;
+ ans = Math.max(ans, f);
+ }
+ return ans;
+}
diff --git a/lcci/16.18.Pattern Matching/README_EN.md b/lcci/16.18.Pattern Matching/README_EN.md
index 14f6d86e948c5..9b9bdebda283f 100644
--- a/lcci/16.18.Pattern Matching/README_EN.md
+++ b/lcci/16.18.Pattern Matching/README_EN.md
@@ -48,6 +48,18 @@
## Solutions
+**Solution 1: Enumeration**
+
+We first count the number of characters `'a'` and `'b'` in the pattern string $pattern,ドル denoted as $cnt[0]$ and $cnt[1],ドル respectively. Let the length of the string $value$ be $n$.
+
+If $cnt[0]=0,ドル it means that the pattern string only contains the character `'b'`. We need to check whether $n$ is a multiple of $cnt[1],ドル and whether $value$ can be divided into $cnt[1]$ substrings of length $n/cnt[1],ドル and all these substrings are the same. If not, return $false$ directly.
+
+If $cnt[1]=0,ドル it means that the pattern string only contains the character `'a'`. We need to check whether $n$ is a multiple of $cnt[0],ドル and whether $value$ can be divided into $cnt[0]$ substrings of length $n/cnt[0],ドル and all these substrings are the same. If not, return $false$ directly.
+
+Next, we denote the length of the string matched by the character `'a'` as $la,ドル and the length of the string matched by the character `'b'` as $lb$. Then we have $la \times cnt[0] + lb \times cnt[1] = n$. If we enumerate $la,ドル we can determine the value of $lb$. Therefore, we can enumerate $la$ and check whether there exists an integer $lb$ that satisfies the above equation.
+
+The time complexity is $O(n^2),ドル and the space complexity is $O(n)$. Here, $n$ is the length of the string $value$.
+
### **Python3**
diff --git a/lcci/16.19.Pond Sizes/README_EN.md b/lcci/16.19.Pond Sizes/README_EN.md
index bd05ddeff9772..9c21c54fa2c84 100644
--- a/lcci/16.19.Pond Sizes/README_EN.md
+++ b/lcci/16.19.Pond Sizes/README_EN.md
@@ -37,6 +37,16 @@
## Solutions
+**Solution 1: DFS**
+
+We can traverse each point $(i, j)$ in the integer matrix $land$. If the value of the point is 0ドル,ドル we start a depth-first search from this point until we reach a point with a non-zero value. The number of points searched during this process is the size of the pond, which is added to the answer array.
+
+> Note: To avoid duplicate searches, we set the value of the searched points to 1ドル$.
+
+Finally, we sort the answer array to obtain the final answer.
+
+The time complexity is $O(m \times n \times \log (m \times n)),ドル and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the number of rows and columns in the matrix $land,ドル respectively.
+
### **Python3**
diff --git a/lcci/16.20.T9/README_EN.md b/lcci/16.20.T9/README_EN.md
index 4bd97da026869..34276644e7d73 100644
--- a/lcci/16.20.T9/README_EN.md
+++ b/lcci/16.20.T9/README_EN.md
@@ -31,6 +31,14 @@
## Solutions
+**Solution 1: Reverse Thinking**
+
+We consider a forward solution, which traverses each digit in the string $num,ドル maps it to the corresponding letter, combines all the letters to obtain all possible words, and then compares them with the given word list. If the word is in the list, it is added to the answer. The time complexity of this solution is $O(4^n),ドル where $n$ is the length of the string $num,ドル which will obviously time out.
+
+Instead, we can consider a reverse solution, which traverses the given word list, and for each word $w,ドル determines whether it can be composed of the digits in the string $num$. If it can be composed, it is added to the answer. The key to the problem is how to determine whether a word can be composed of the digits in the string $num$. We only need to traverse each letter in the word $w,ドル restore it to the corresponding digit, and compare it with each digit in the string $num$ one by one. If they are the same, it means that the word $w$ can be composed of the digits in the string $num$.
+
+The time complexity is $O(m \times n),ドル and the space complexity is $O(C)$. Here, $m$ and $n$ are the length of the word list and the string $num,ドル respectively, and $C$ is the size of the character set, which is 26ドル$ in this problem.
+
### **Python3**
diff --git a/lcci/16.21.Sum Swap/README_EN.md b/lcci/16.21.Sum Swap/README_EN.md
index 8ed96cae002dd..b21835b493e3b 100644
--- a/lcci/16.21.Sum Swap/README_EN.md
+++ b/lcci/16.21.Sum Swap/README_EN.md
@@ -34,6 +34,14 @@
## Solutions
+**Solution 1: Hash Table**
+
+We first calculate the sum of the two arrays, and then calculate the difference $diff$ between the sums. If $diff$ is odd, it means that the sums of the two arrays cannot be equal, so we directly return an empty array.
+
+If $diff$ is even, we can traverse one of the arrays. Suppose the current element being traversed is $a,ドル then we need to find an element $b$ in the other array such that $a - b = diff / 2,ドル i.e., $b = a - diff / 2$. We can use a hash table to quickly check whether $b$ exists. If it exists, it means that we have found a pair of elements that meet the conditions, and we can return them directly.
+
+The time complexity is $O(m + n),ドル and the space complexity is $O(n)$. Here, $m$ and $n$ are the lengths of the two arrays.
+
### **Python3**
diff --git a/lcci/16.22.Langtons Ant/README_EN.md b/lcci/16.22.Langtons Ant/README_EN.md
index d9d10b728014d..9f2eaf5bb160c 100644
--- a/lcci/16.22.Langtons Ant/README_EN.md
+++ b/lcci/16.22.Langtons Ant/README_EN.md
@@ -59,6 +59,16 @@
## Solutions
+**Solution 1: Hash Table + Simulation**
+
+We use a hash table $black$ to record the positions of all black squares, and a hash table $dirs$ to record the four directions of the ant. We use variables $x, y$ to record the position of the ant, and variable $p$ to record the direction of the ant. We use variables $x1, y1, x2, y2$ to record the minimum horizontal coordinate, minimum vertical coordinate, maximum horizontal coordinate, and maximum vertical coordinate of all black squares.
+
+We simulate the ant's walking process. If the square where the ant is located is white, the ant turns right by 90ドル$ degrees, paints the square black, and moves forward one unit. If the square where the ant is located is black, the ant turns left by 90ドル$ degrees, paints the square white, and moves forward one unit. During the simulation, we continuously update the values of $x1, y1, x2, y2$ so that they can contain all the squares the ant has walked through.
+
+After the simulation is over, we construct the answer matrix $g$ based on the values of $x1, y1, x2, y2$. Then, we paint the direction of the ant on the square where the ant is located, paint all black squares with $X,ドル and finally return the answer matrix.
+
+The time complexity is $O(K),ドル and the space complexity is $O(K)$. Here, $K$ is the number of steps the ant walks.
+
### **Python3**
diff --git a/lcci/16.24.Pairs With Sum/README_EN.md b/lcci/16.24.Pairs With Sum/README_EN.md
index 0bb23f1448c7b..88fac50820e19 100644
--- a/lcci/16.24.Pairs With Sum/README_EN.md
+++ b/lcci/16.24.Pairs With Sum/README_EN.md
@@ -24,6 +24,16 @@
## Solutions
+**Solution 1: Hash Table**
+
+We can use a hash table to store the elements in the array, with the keys being the elements in the array and the values being the number of times the element appears.
+
+We traverse the array, and for each element $x,ドル we calculate $y = target - x$. If $y$ exists in the hash table, it means that there is a pair of numbers $(x, y)$ that add up to the target, and we add it to the answer and reduce the count of $y$ by 1ドル$. If $y$ does not exist in the hash table, it means that there is no such pair of numbers, and we increase the count of $x$ by 1ドル$.
+
+After the traversal, we can obtain the answer.
+
+The time complexity is $O(n),ドル and the space complexity is $O(n)$. Here, $n$ is the length of the array.
+
### **Python3**