diff --git a/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md b/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md index 0c9d567adc4f0..d54248ce22f05 100644 --- a/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md +++ b/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md @@ -80,7 +80,7 @@ nums[3] + nums[0] = 3 + 1 = 4. 可以发现,这实际上是在对一个连续区间内的元素进行加减操作,因此我们可以使用差分数组来实现。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 diff --git a/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md b/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md index 9ee7af3515036..b1429576b6fdc 100644 --- a/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md +++ b/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md @@ -52,6 +52,30 @@ Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary. ## Solutions +**Solution 1: Difference Array** + +Let's denote $a$ as the smaller value between $nums[i]$ and $nums[n-i-1]$, and $b$ as the larger value between $nums[i]$ and $nums[n-i-1]$. + +Suppose that after replacement, the sum of the two numbers is $x$. From the problem, we know that the minimum value of $x$ is $2$, which means both numbers are replaced by $1$; the maximum value is $2 \times limit$, which means both numbers are replaced by $limit$. Therefore, the range of $x$ is $[2,... 2 \times limit]$. + +How to find the minimum number of replacements for different $x$? + +We analyze and find: + +- If $x = a + b$, then the number of replacements we need is $0$, which means the current pair of numbers already meets the complement requirement; +- Otherwise, if $1 + a \le x \le limit + b $, then the number of replacements we need is $1$, which means we can replace one of the numbers; +- Otherwise, if $2 \le x \le 2 \times limit$, then the number of replacements we need is $2$, which means we need to replace both numbers. + +Therefore, we can iterate over each pair of numbers and perform the following operations: + +1. First, add $2$ to the number of operations required in the range $[2,... 2 \times limit]$. +1. Then, subtract $1$ from the number of operations required in the range $[1 + a,... limit + b]$. +1. Finally, subtract $1$ from the number of operations required in the range $[a + b,... a + b]$. + +We can see that this is actually adding and subtracting elements in a continuous interval, so we can use a difference array to implement it. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + ### **Python3** diff --git a/solution/1600-1699/1675.Minimize Deviation in Array/README_EN.md b/solution/1600-1699/1675.Minimize Deviation in Array/README_EN.md index bd2f74e720f22..65a7366b82fa0 100644 --- a/solution/1600-1699/1675.Minimize Deviation in Array/README_EN.md +++ b/solution/1600-1699/1675.Minimize Deviation in Array/README_EN.md @@ -60,6 +60,18 @@ ## Solutions +**Solution 1: Greedy + Priority Queue** + +Intuitively, to get the minimum offset of the array, we need to decrease the maximum value of the array and increase the minimum value of the array. + +Since there are two operations that can be performed each time: multiply an odd number by $2$; divide an even number by $2$, the situation is more complex. We can multiply all odd numbers by $2$ to convert them into even numbers, which is equivalent to having only one division operation. The division operation can only reduce a certain number, and only by reducing the maximum value can the result be more optimal. + +Therefore, we use a priority queue (max heap) to maintain the maximum value of the array. Each time we take out the top element of the heap for division operation, put the new value into the heap, and update the minimum value and the minimum value of the difference between the top element of the heap and the minimum value. + +When the top element of the heap is an odd number, the operation stops. + +The time complexity is $O(n\log n \times \log m)$. Where $n$ and $m$ are the length of the array `nums` and the maximum element of the array, respectively. Since the maximum element in the array is divided by $2$ at most $O(\log m)$ times, all elements are divided by $2$ at most $O(n\log m)$ times. Each time the heap is popped and put into operation, the time complexity is $O(\log n)$. Therefore, the total time complexity is $O(n\log n \times \log m)$. + ### **Python3** diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/README_EN.md b/solution/1600-1699/1678.Goal Parser Interpretation/README_EN.md index 70fd97acc9527..cf6aec728af88 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/README_EN.md +++ b/solution/1600-1699/1678.Goal Parser Interpretation/README_EN.md @@ -45,6 +45,21 @@ The final concatenated result is "Goal". ## Solutions +**Solution 1: String Replacement** + +According to the problem, we only need to replace `"()"` with `'o'` and `"(al)"` with `"al"` in the string `command`. + +**Solution 2: String Iteration** + +We can also iterate over the string `command`. For each character $c$: + +- If it is `'G'`, directly add $c$ to the result string; +- If it is `'('`, check if the next character is `')'`. If it is, add `'o'` to the result string. Otherwise, add `"al"` to the result string. + +After the iteration, return the result string. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/README.md b/solution/1600-1699/1679.Max Number of K-Sum Pairs/README.md index 78f0ace35c224..5d0eeb81c6323 100644 --- a/solution/1600-1699/1679.Max Number of K-Sum Pairs/README.md +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/README.md @@ -49,7 +49,7 @@ **方法一:排序** -我们对 `nums` 进行排序。然后 $l$, $r$ 分别指向 `nums` 首尾元素,判断两整数之和 $s$ 与 $k$ 的大小关系。 +我们对 $nums$ 进行排序。然后 $l$, $r$ 分别指向 $nums$ 首尾元素,判断两整数之和 $s$ 与 $k$ 的大小关系。 - 若 $s = k$,说明找到了两个整数,满足和为 $k$,答案加一,然后 $l$, $r$ 向中间移动; - 若 $s \gt k$,则 $r$ 指针向左移动; @@ -58,17 +58,17 @@ 循环结束,返回答案。 -时间复杂度 $O(n\times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为 `nums` 的长度。 +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为 $nums$ 的长度。 **方法二:哈希表** -我们使用哈希表 `cnt` 记录当前剩余整数及其出现的次数。 +我们使用哈希表 $cnt$ 记录当前剩余整数及其出现的次数。 -遍历 `nums`,对于当前整数 $x$,判断 $k - x$ 是否在 `cnt` 中,若存在,则说明找到了两个整数,满足和为 $k$,答案加一,然后将 $k - x$ 的出现次数减一;否则,将 $x$ 的出现次数加一。 +遍历 $nums$,对于当前整数 $x$,判断 $k - x$ 是否在 $cnt$ 中,若存在,则说明找到了两个整数,满足和为 $k$,答案加一,然后将 $k - x$ 的出现次数减一;否则,将 $x$ 的出现次数加一。 遍历结束,返回答案。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `nums` 的长度。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 $nums$ 的长度。 diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md b/solution/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md index f32579d1cf0b7..a0eb5cd7669ea 100644 --- a/solution/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md @@ -41,6 +41,29 @@ There are no more pairs that sum up to 6, hence a total of 1 operation. ## Solutions +**Solution 1: Sorting** + +We sort $nums$. Then $l$ and $r$ point to the first and last elements of $nums$ respectively, and we compare the sum $s$ of the two integers with $k$. + +- If $s = k$, it means that we have found two integers whose sum is $k$. We increment the answer and then move $l$ and $r$ towards the middle; +- If $s > k$, then we move the $r$ pointer to the left; +- If $s < k$, then we move the $l$ pointer to the right; +- We continue the loop until $l \geq r$. + +After the loop ends, we return the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of $nums$. + +**Solution 2: Hash Table** + +We use a hash table $cnt$ to record the current remaining integers and their occurrence counts. + +We iterate over $nums$. For the current integer $x$, we check if $k - x$ is in $cnt$. If it exists, it means that we have found two integers whose sum is $k$. We increment the answer and then decrement the occurrence count of $k - x$; otherwise, we increment the occurrence count of $x$. + +After the iteration ends, we return the answer. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of $nums$. + ### **Python3** diff --git a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README.md b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README.md index ee15a29fc66c8..a611a068b7b51 100644 --- a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README.md +++ b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README.md @@ -50,7 +50,7 @@ 观察数字的连接规律,我们可以发现,当连接到第 $i$ 个数时,实际上是将前 $i-1$ 个数连接而成的结果 $ans$ 往左移动一定的位数,然后再加上 $i$ 这个数,移动的位数 $shift$ 是 $i$ 中二进制的位数。由于 $i$ 在不断加 $1$,移动的位数要么与上一次移动的位数保持不变,要么加一。当 $i$ 为 $2$ 的幂次方的时候,也即是说 $i$ 的二进制数中只有一位是 $1$ 时,移动的位数相比于上次加 $1$。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。 +时间复杂度 $O(n)$,其中 $n$ 为给定的整数。空间复杂度 $O(1)$。 diff --git a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md index ff0fe7f7410d6..327a29556a8ab 100644 --- a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md +++ b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md @@ -43,6 +43,12 @@ After modulo 109 + 7, the result is 505379714. ## Solutions +**Solution 1: Bit Manipulation** + +By observing the pattern of number concatenation, we can find that when concatenating to the $i$-th number, the result $ans$ formed by concatenating the previous $i-1$ numbers is actually shifted to the left by a certain number of bits, and then $i$ is added. The number of bits shifted, $shift$, is the number of binary digits in $i$. Since $i$ is continuously incremented by $1$, the number of bits shifted either remains the same as the last shift or increases by one. When $i$ is a power of $2$, that is, when there is only one bit in the binary number of $i$ that is $1$, the number of bits shifted increases by $1$ compared to the last time. + +The time complexity is $O(n)$, where $n$ is the given integer. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1600-1699/1681.Minimum Incompatibility/README_EN.md b/solution/1600-1699/1681.Minimum Incompatibility/README_EN.md index a580e46978b97..6b9e0636b051f 100644 --- a/solution/1600-1699/1681.Minimum Incompatibility/README_EN.md +++ b/solution/1600-1699/1681.Minimum Incompatibility/README_EN.md @@ -50,6 +50,22 @@ The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6. ## Solutions +**Solution 1: Preprocessing + State Compression + Dynamic Programming** + +Let's assume that the size of each subset after partitioning is $m$, so $m=\frac{n}{k}$, where $n$ is the length of the array. + +We can enumerate all subsets $i$, where $i \in [0, 2^n)$, if the binary representation of subset $i$ has $m$ ones, and the elements in subset $i$ are not repeated, then we can calculate the incompatibility of subset $i$, denoted as $g[i]$, i.e., $g[i]=\max_{j \in i} \{nums[j]\} - \min_{j \in i} \{nums[j]\}$. + +Next, we can use dynamic programming to solve. + +We define $f[i]$ as the minimum sum of incompatibilities when the current partitioned subset state is $i$. Initially, $f[0]=0$, which means no elements are partitioned into the subset, and the rest $f[i]=+\infty$. + +For state $i$, we find all undivided and non-repeated elements, represented by a state $mask$. If the number of elements in state $mask$ is greater than or equal to $m$, then we enumerate all subsets $j$ of $mask$, and satisfy $j \subset mask$, then $f[i \cup j]=\min \{f[i \cup j], f[i]+g[j]\}$. + +Finally, if $f[2^n-1]=+\infty$, it means that it cannot be partitioned into $k$ subsets, return $-1$, otherwise return $f[2^n-1]$. + +The time complexity is $O(3^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the length of the array. + ### **Python3** diff --git a/solution/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md b/solution/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md index ddbf89d66e546..74d69ad05cf4f 100644 --- a/solution/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md +++ b/solution/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md @@ -44,6 +44,20 @@ ## Solutions +**Solution 1: Memorization Search** + +We design a function $dfs(i, j, x)$ to represent the length of the longest "good" palindrome subsequence ending with character $x$ in the index range $[i, j]$ of string $s$. The answer is $dfs(0, n - 1, 26)$. + +The calculation process of the function $dfs(i, j, x)$ is as follows: + +- If $i >= j$, then $dfs(i, j, x) = 0$; +- If $s[i] = s[j]$ and $s[i] \neq x$, then $dfs(i, j, x) = dfs(i + 1, j - 1, s[i]) + 2$; +- If $s[i] \neq s[j]$, then $dfs(i, j, x) = max(dfs(i + 1, j, x), dfs(i, j - 1, x))$. + +During the process, we can use memorization search to avoid repeated calculations. + +The time complexity is $O(n^2 \times C)$. Where $n$ is the length of the string $s$, and $C$ is the size of the character set. In this problem, $C = 26$. + ### **Python3** diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/README.md b/solution/1600-1699/1684.Count the Number of Consistent Strings/README.md index 92de0807d7cdf..34e665744e857 100644 --- a/solution/1600-1699/1684.Count the Number of Consistent Strings/README.md +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/README.md @@ -66,7 +66,7 @@ 回到题目上,判断一个字符串 $w$ 是否由 `allowed` 中的字符组成,就可以转换为:判断 $f(allowed)$ 和 $f(w)$ 进行按位或运算后的结果是否等于 $f(allowed)$。若是,答案加一。 -时间复杂度 $O(m)$,空间复杂度 $O(1)$。其中 $m$ 为所有字符串的总长度。 +时间复杂度 $O(m)$,其中 $m$ 为所有字符串的总长度。空间复杂度 $O(1)$。 diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md b/solution/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md index 2d9d38e86bf12..8955025943bf1 100644 --- a/solution/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md @@ -46,6 +46,22 @@ ## Solutions +**Solution 1: Hash Table or Array** + +A straightforward approach is to use a hash table or array $s$ to record the characters in `allowed`. Then iterate over the `words` array, for each string $w$, determine whether it is composed of characters in `allowed`. If so, increment the answer. + +The time complexity is $O(m)$, and the space complexity is $O(C)$. Here, $m$ is the total length of all strings, and $C$ is the size of the character set `allowed`. In this problem, $C \leq 26$. + +**Solution 2: Bit Manipulation** + +We can also use a single integer to represent the occurrence of characters in each string. In this integer, each bit in the binary representation indicates whether a character appears. + +We simply define a function $f(w)$ that can convert a string $w$ into an integer. Each bit in the binary representation of the integer indicates whether a character appears. For example, the string `ab` can be converted into the integer $3$, which is represented in binary as $11$. The string `abd` can be converted into the integer $11$, which is represented in binary as $1011$. + +Back to the problem, to determine whether a string $w$ is composed of characters in `allowed`, we can check whether the result of the bitwise OR operation between $f(allowed)$ and $f(w)$ is equal to $f(allowed)$. If so, increment the answer. + +The time complexity is $O(m)$, where $m$ is the total length of all strings. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README.md b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README.md index 304853838db24..408539f1915c3 100644 --- a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README.md +++ b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README.md @@ -47,11 +47,11 @@ result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5。 **方法一:求和 + 枚举** -我们先求出数组 `nums` 所有元素的和,记为 $s$,用变量 $t$ 记录当前已经枚举过的元素之和。 +我们先求出数组 $nums$ 所有元素的和,记为 $s$,用变量 $t$ 记录当前已经枚举过的元素之和。 接下来枚举 $nums[i]$,那么 $ans[i] = nums[i] \times i - t + s - t - nums[i] \times (n - i)$,然后我们更新 $t$,即 $t = t + nums[i]$。继续枚举下一个元素,直到枚举完所有元素。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。 diff --git a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md index 42a4fcae266d8..8ddeb18d733fa 100644 --- a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md +++ b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md @@ -39,6 +39,14 @@ result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. ## Solutions +**Solution 1: Summation + Enumeration** + +First, we calculate the sum of all elements in the array $nums$, denoted as $s$. We use a variable $t$ to record the sum of the elements that have been enumerated so far. + +Next, we enumerate $nums[i]$. Then $ans[i] = nums[i] \times i - t + s - t - nums[i] \times (n - i)$. After that, we update $t$, i.e., $t = t + nums[i]$. We continue to enumerate the next element until all elements are enumerated. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1600-1699/1686.Stone Game VI/README.md b/solution/1600-1699/1686.Stone Game VI/README.md index 3091e4e47a70d..259cd2f0203ae 100644 --- a/solution/1600-1699/1686.Stone Game VI/README.md +++ b/solution/1600-1699/1686.Stone Game VI/README.md @@ -74,7 +74,7 @@ Bob 会获胜。 选取石头的最优化的策略是,让自己得分最高,同时让对手失分最多。因此,我们创建一个数组 `arr`,其中 `arr[i] = aliceValues[i] + bobValues[i]`,然后对 `arr` 进行降序排序。然后,我们从 `arr` 中取出石头,每次取出两个石头,分别给 Alice 和 Bob,直到 `arr` 中没有石头为止。最后,我们比较 Alice 和 Bob 的得分,得分高的人获胜。 -时间复杂度 $O(n\log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `aliceValues` 和 `bobValues` 的长度。 +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `aliceValues` 和 `bobValues` 的长度。 diff --git a/solution/1600-1699/1686.Stone Game VI/README_EN.md b/solution/1600-1699/1686.Stone Game VI/README_EN.md index 3a1bc061e6802..2144944556eb1 100644 --- a/solution/1600-1699/1686.Stone Game VI/README_EN.md +++ b/solution/1600-1699/1686.Stone Game VI/README_EN.md @@ -64,6 +64,12 @@ Bob wins. ## Solutions +**Solution 1: Greedy + Sorting** + +The optimal strategy for picking stones is to maximize one's own score while making the opponent lose as much as possible. Therefore, we create an array `arr`, where `arr[i] = aliceValues[i] + bobValues[i]`, and then sort `arr` in descending order. Then, we take stones from `arr`, taking two stones each time, one for Alice and one for Bob, until there are no stones left in `arr`. Finally, we compare the scores of Alice and Bob, and the person with the higher score wins. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the arrays `aliceValues` and `bobValues`. + ### **Python3** diff --git a/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README.md b/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README.md index 01853b769b9bd..d8731e450f4ca 100644 --- a/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README.md +++ b/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README.md @@ -228,7 +228,7 @@ func boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) i 本题数据规模达到 $10^5$,而以上代码的时间复杂度为 $O(n^2)$,会超出时间限制。我们仔细观察: $$ -f[i] = min(f[i], f[j] + cs[i - 1] - cs[j] + 2) +f[i] = \min(f[i], f[j] + cs[i - 1] - cs[j] + 2) $$ 实际上我们是要在 $[i-maxBoxes,..i-1]$ 这个窗口内找到一个 $j$,使得 $f[j] - cs[j]$ 的值最小,求滑动窗口的最小值,一种常用的做法是使用单调队列,可以在 $O(1)$ 时间内获取到满足条件的最小值。 diff --git a/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md b/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md index e0a329954526a..514b169e5a0f6 100644 --- a/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md +++ b/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md @@ -74,6 +74,146 @@ So the total number of trips is 2 + 2 + 2 = 6. ## Solutions +**Solution 1: Dynamic Programming + Monotonic Queue Optimization** + +We define $f[i]$ as the minimum number of trips required to transport the first $i$ boxes from the warehouse to the corresponding docks, so the answer is $f[n]$. + +The boxes need to be transported in the order of the array. Each time, the truck will take out several consecutive boxes in order, then deliver them to the corresponding docks one by one. After all are delivered, it returns to the warehouse. + +Therefore, we can enumerate the index $j$ of the last box transported in the last trip. Then $f[i]$ can be transferred from $f[j]$. During the transfer, we need to consider the following issues: + +- When transferring from $f[j]$, the number of boxes on the truck cannot exceed $maxBoxes$ +- When transferring from $f[j]$, the total weight of the boxes on the truck cannot exceed $maxWeight$ + +The state transition equation is: + +$$ +f[i] = \min_{j \in [i - maxBoxes, i - 1]} \left(f[j] + \sum_{k = j + 1}^i \text{cost}(k)\right) +$$ + +Where $\sum_{k = j + 1}^i \text{cost}(k)$ represents the number of trips required to deliver the boxes in $[j+1,..i]$ to their corresponding docks in one trip. This part of the trip count can be quickly calculated using prefix sums. + +For example, suppose we take out boxes $1, 2, 3$ and need to deliver them to docks $4, 4, 5$. We first go from the warehouse to dock $4$, then from dock $4$ to dock $5$, and finally from dock $5$ back to the warehouse. It can be seen that it takes $2$ trips to go from the warehouse to the dock and from the dock back to the warehouse. The number of trips from dock to dock depends on whether the two adjacent docks are the same. If they are not the same, the number of trips will increase by $1$, otherwise it remains the same. Therefore, we can calculate the number of trips between docks using prefix sums, and add two trips for the start and end, to calculate the number of trips required to deliver the boxes in $[j+1,..i]$ to their corresponding docks. + +The code implementation is as follows: + +```python +# 33/39 +class Solution: + def boxDelivering( + self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int + ) -> int: + n = len(boxes) + ws = list(accumulate((box[1] for box in boxes), initial=0)) + c = [int(a != b) for a, b in pairwise(box[0] for box in boxes)] + cs = list(accumulate(c, initial=0)) + f = [inf] * (n + 1) + f[0] = 0 + for i in range(1, n + 1): + for j in range(max(0, i - maxBoxes), i): + if ws[i] - ws[j] <= maxWeight: + f[i] = min(f[i], f[j] + cs[i - 1] - cs[j] + 2) + return f[n] +``` + +```java +// 35/39 +class Solution { + public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { + int n = boxes.length; + long[] ws = new long[n + 1]; + int[] cs = new int[n]; + for (int i = 0; i < n; ++i) { + int p = boxes[i][0], w = boxes[i][1]; + ws[i + 1] = ws[i] + w; + if (i < n - 1) { + cs[i + 1] = cs[i] + (p != boxes[i + 1][0] ? 1 : 0); + } + } + int[] f = new int[n + 1]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = Math.max(0, i - maxBoxes); j < i; ++j) { + if (ws[i] - ws[j] <= maxWeight) { + f[i] = Math.min(f[i], f[j] + cs[i - 1] - cs[j] + 2); + } + } + } + return f[n]; + } +} +``` + +```cpp +// 35/39 +class Solution { +public: + int boxDelivering(vector>& boxes, int portsCount, int maxBoxes, int maxWeight) { + int n = boxes.size(); + long ws[n + 1]; + int cs[n]; + ws[0] = cs[0] = 0; + for (int i = 0; i < n; ++i) { + int p = boxes[i][0], w = boxes[i][1]; + ws[i + 1] = ws[i] + w; + if (i < n - 1) cs[i + 1] = cs[i] + (p != boxes[i + 1][0]); + } + int f[n + 1]; + memset(f, 0x3f, sizeof f); + f[0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = max(0, i - maxBoxes); j < i; ++j) { + if (ws[i] - ws[j] <= maxWeight) { + f[i] = min(f[i], f[j] + cs[i - 1] - cs[j] + 2); + } + } + } + return f[n]; + } +}; +``` + +```go +// 35/39 +func boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) int { + n := len(boxes) + ws := make([]int, n+1) + cs := make([]int, n) + for i, box := range boxes { + p, w := box[0], box[1] + ws[i+1] = ws[i] + w + if i < n-1 { + t := 0 + if p != boxes[i+1][0] { + t++ + } + cs[i+1] = cs[i] + t + } + } + f := make([]int, n+1) + for i := 1; i <= n; i++ { + f[i] = 1 << 30 + for j := max(0, i-maxBoxes); j < i; j++ { + if ws[i]-ws[j] <= maxWeight { + f[i] = min(f[i], f[j]+cs[i-1]-cs[j]+2) + } + } + } + return f[n] +} +``` + +The data scale of this problem reaches $10^5$, and the time complexity of the above code is $O(n^2)$, which will exceed the time limit. If we observe carefully: + +$$ +f[i] = \min(f[i], f[j] + cs[i - 1] - cs[j] + 2) +$$ + +In fact, we are looking for a $j$ in the window $[i-maxBoxes,..i-1]$ that minimizes the value of $f[j] - cs[j]$. To find the minimum value in a sliding window, a common method is to use a monotonic queue, which can get the minimum value that meets the condition in $O(1)$ time. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of boxes in the problem. + ### **Python3** diff --git a/solution/1600-1699/1688.Count of Matches in Tournament/README_EN.md b/solution/1600-1699/1688.Count of Matches in Tournament/README_EN.md index c50b2c1d9f191..e010bbf8300f6 100644 --- a/solution/1600-1699/1688.Count of Matches in Tournament/README_EN.md +++ b/solution/1600-1699/1688.Count of Matches in Tournament/README_EN.md @@ -48,6 +48,12 @@ Total number of matches = 7 + 3 + 2 + 1 = 13. ## Solutions +**Solution 1: Quick Thinking** + +From the problem description, we know that there are $n$ teams in total. Each pairing will eliminate one team. Therefore, the number of pairings is equal to the number of teams eliminated, which is $n - 1$. + +The time complexity is $O(1)$, and the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README.md b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README.md index 058758548a3bb..096c65ba84b65 100644 --- a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README.md +++ b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README.md @@ -49,7 +49,7 @@ 题目等价于找字符串中的最大数。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串长度。 +时间复杂度 $O(n)$,其中 $n$ 为字符串长度。空间复杂度 $O(1)$。 diff --git a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md index 3d9af94570b29..83b2b13c1e64b 100644 --- a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md +++ b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md @@ -42,6 +42,12 @@ ## Solutions +**Solution 1: Quick Thinking** + +The problem is equivalent to finding the maximum number in the string. + +The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1600-1699/1690.Stone Game VII/README_EN.md b/solution/1600-1699/1690.Stone Game VII/README_EN.md index 12f4a7e7748f3..42abd46bff4b7 100644 --- a/solution/1600-1699/1690.Stone Game VII/README_EN.md +++ b/solution/1600-1699/1690.Stone Game VII/README_EN.md @@ -44,6 +44,21 @@ The score difference is 18 - 12 = 6. ## Solutions +**Solution 1: Memorization Search** + +First, we preprocess to get the prefix sum array $s$, where $s[i]$ represents the total sum of the first $i$ stones. + +Next, we design a function $dfs(i, j)$, which represents the score difference between the first and second players when the remaining stones are $stones[i], stones[i + 1], \dots, stones[j]$. The answer is $dfs(0, n - 1)$. + +The calculation process of the function $dfs(i, j)$ is as follows: + +- If $i > j$, it means there are no stones currently, so return $0$; +- Otherwise, the first player has two choices, which are to remove $stones[i]$ or $stones[j]$, and then calculate the score difference, i.e., $a = s[j + 1] - s[i + 1] - dfs(i + 1, j)$ and $b = s[j] - s[i] - dfs(i, j - 1)$. We take the larger of the two as the return value of $dfs(i, j)$. + +During the process, we use memorization search, i.e., use an array $f$ to record the return value of the function $dfs(i, j)$, to avoid repeated calculations. + +The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the number of stones. + ### **Python3** diff --git a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md index 60ff3a2235075..82a9e018fb25d 100644 --- a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md +++ b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md @@ -57,6 +57,28 @@ The maximum height of stacked cuboids is 6 * 17 = 102. ## Solutions +**Solution 1: Sorting + Dynamic Programming** + +According to the problem description, box $j$ can be placed on box $i$ if and only if the "length, width, and height" of box $j$ are less than or equal to the "length, width, and height" of box $i$. + +This problem allows us to rotate the boxes, which means we can choose any side of the box as the "height". For any legal stacking, if we rotate each box in it to "length <= width <= height", the stacking is still legal and can ensure the maximum height of the stacking. + +Therefore, we can sort all the sides of the boxes so that each box satisfies "length <= width <= height". Then we sort each box in ascending order. + +Next, we can use dynamic programming to solve this problem. + +We define $f[i]$ as the maximum height when box $i$ is at the bottom. We can enumerate each box $j$ above box $i$, where $0 \leq j < i$. If $j$ can be placed on top of $i$, then we can get the state transition equation: + +$$ +f[i] = \max_{0 \leq j < i} \{f[j] + h[i]\} +$$ + +where $h[i]$ represents the height of box $i$. + +The final answer is the maximum value of $f[i]$. + +The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the number of boxes. + ### **Python3** diff --git a/solution/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md b/solution/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md index 5d30a7c0f6021..8c82322f63086 100644 --- a/solution/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md +++ b/solution/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md @@ -58,6 +58,20 @@ ## Solutions +**Solution 1: Dynamic Programming** + +We define $f[i][j]$ as the number of different ways to distribute $i$ candies to $j$ bags. Initially, $f[0][0]=1$, and the answer is $f[n][k]$. + +We consider how to distribute the $i$-th candy. If the $i$-th candy is distributed to a new bag, then $f[i][j]=f[i-1][j-1]$. If the $i$-th candy is distributed to an existing bag, then $f[i][j]=f[i-1][j]\times j$. Therefore, the state transition equation is: + +$$ +f[i][j]=f[i-1][j-1]+f[i-1][j]\times j +$$ + +The final answer is $f[n][k]$. + +The time complexity is $O(n \times k)$, and the space complexity is $O(n \times k)$. Here, $n$ and $k$ are the number of candies and bags, respectively. + ### **Python3** diff --git a/solution/1600-1699/1694.Reformat Phone Number/README.md b/solution/1600-1699/1694.Reformat Phone Number/README.md index 0115e0288e5d0..16d2e32fa98ed 100644 --- a/solution/1600-1699/1694.Reformat Phone Number/README.md +++ b/solution/1600-1699/1694.Reformat Phone Number/README.md @@ -89,7 +89,7 @@ **方法一:简单模拟** -先按照题意,去除字符串中的所有空格和破折号。 +我们先按照题意,去除字符串中的所有空格和破折号。 记当前字符串长度为 $n$,然后从前往后遍历字符串,每 $3$ 个字符为一组,将其加入结果字符串中,共取 $n / 3$ 组。 diff --git a/solution/1600-1699/1694.Reformat Phone Number/README_EN.md b/solution/1600-1699/1694.Reformat Phone Number/README_EN.md index 038becf2e7c94..47b0fcf8a4f5e 100644 --- a/solution/1600-1699/1694.Reformat Phone Number/README_EN.md +++ b/solution/1600-1699/1694.Reformat Phone Number/README_EN.md @@ -64,6 +64,18 @@ Joining the blocks gives "123-456-78". ## Solutions +**Solution 1: Simple Simulation** + +First, according to the problem description, we remove all spaces and hyphens from the string. + +Let the current string length be $n$. Then we traverse the string from the beginning, grouping every $3$ characters together and adding them to the result string. We take a total of $n / 3$ groups. + +If there is $1$ character left in the end, we form a new group of two characters with the last character of the last group and this character, and add it to the result string. If there are $2$ characters left, we directly form a new group with these two characters and add it to the result string. + +Finally, we add hyphens between all groups and return the result string. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string. + ### **Python3** diff --git a/solution/1600-1699/1695.Maximum Erasure Value/README.md b/solution/1600-1699/1695.Maximum Erasure Value/README.md index 34662bd76e697..bb54ade5a57da 100644 --- a/solution/1600-1699/1695.Maximum Erasure Value/README.md +++ b/solution/1600-1699/1695.Maximum Erasure Value/README.md @@ -49,7 +49,7 @@ 遍历数组,对于每个数字 $v$,如果 $d[v]$ 存在,那么我们更新 $j$ 为 $max(j, d[v])$,这样就保证了当前不重复子数组不包含 $v$,然后更新答案为 $max(ans, s[i] - s[j])$,最后更新 $d[v]$ 为 $i$。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 diff --git a/solution/1600-1699/1695.Maximum Erasure Value/README_EN.md b/solution/1600-1699/1695.Maximum Erasure Value/README_EN.md index d66b316c34003..8d6cf74902403 100644 --- a/solution/1600-1699/1695.Maximum Erasure Value/README_EN.md +++ b/solution/1600-1699/1695.Maximum Erasure Value/README_EN.md @@ -37,6 +37,14 @@ ## Solutions +**Solution 1: Array or Hash Table + Prefix Sum** + +We use an array or hash table $d$ to record the last occurrence of each number, use $s$ to record the prefix sum, and use $j$ to record the left endpoint of the current non-repeating subarray. + +We traverse the array, for each number $v$, if $d[v]$ exists, then we update $j$ to $max(j, d[v])$, which ensures that the current non-repeating subarray does not contain $v$. Then we update the answer to $max(ans, s[i] - s[j])$, and finally update $d[v]$ to $i$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + ### **Python3** diff --git a/solution/1600-1699/1696.Jump Game VI/README_EN.md b/solution/1600-1699/1696.Jump Game VI/README_EN.md index ec7d1e60f7411..bc2b29d3aff27 100644 --- a/solution/1600-1699/1696.Jump Game VI/README_EN.md +++ b/solution/1600-1699/1696.Jump Game VI/README_EN.md @@ -46,6 +46,20 @@ ## Solutions +**Solution 1: Dynamic Programming + Monotonic Queue Optimization** + +We define $f[i]$ as the maximum score when reaching index $i$. The value of $f[i]$ can be transferred from $f[j]$, where $j$ satisfies $i - k \leq j \leq i - 1$. Therefore, we can use dynamic programming to solve this problem. + +The state transition equation is: + +$$ +f[i] = \max_{j \in [i - k, i - 1]} f[j] + nums[i] +$$ + +We can use a monotonic queue to optimize the state transition equation. Specifically, we maintain a monotonically decreasing queue, which stores the index $j$, and the $f[j]$ values corresponding to the indices in the queue are monotonically decreasing. When performing state transition, we only need to take out the index $j$ at the front of the queue to get the maximum value of $f[j]$, and then update the value of $f[i]$ to $f[j] + nums[i]$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. + ### **Python3** diff --git a/solution/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md b/solution/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md index 5f9f13e86b760..7ed32b5830f4b 100644 --- a/solution/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md +++ b/solution/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md @@ -37,6 +37,24 @@ ## Solutions +**Solution 1: Brute Force Enumeration** + +Enumerate all substrings and use a hash table to record the count of different substrings. + +The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string. + +**Solution 2: String Hashing** + +**String hashing** is a method to map a string of any length to a non-negative integer, and the probability of collision is almost zero. String hashing is used to calculate the hash value of a string, which can quickly determine whether two strings are equal. + +We take a fixed value BASE, treat the string as a number in BASE radix, and assign a value greater than 0 to represent each character. Generally, the values we assign are much smaller than BASE. For example, for a string composed of lowercase letters, we can set a=1, b=2, ..., z=26. We take a fixed value MOD, calculate the remainder of the BASE radix number to MOD, and use it as the hash value of the string. + +Generally, we take BASE=131 or BASE=13331, at which point the probability of collision of the hash value is extremely low. As long as the hash values of two strings are the same, we consider the two strings to be equal. Usually, MOD is taken as 2^64. In C++, we can directly use the unsigned long long type to store this hash value. When calculating, we do not handle arithmetic overflow. When overflow occurs, it is equivalent to automatically taking the modulus of 2^64, which can avoid inefficient modulus operations. + +Except for extremely specially constructed data, the above hash algorithm is unlikely to cause collisions. In general, the above hash algorithm can appear in the standard answer of the problem. We can also take some appropriate BASE and MOD values (such as large prime numbers), perform several groups of hash operations, and only consider the original strings equal when the results are all the same, making it even more difficult to construct data that causes this hash to produce errors. + +The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string. + ### **Python3** diff --git a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README.md b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README.md index 5e66b06887679..f9db8488fcd89 100644 --- a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README.md +++ b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README.md @@ -61,13 +61,13 @@ 我们观察发现,学生位置可调整,而三明治位置不可调整。也就是说,若前面的三明治没被拿走,则往后的所有三明治也无法被拿走。 -因此,我们先用计数器 `cnt` 统计学生喜欢的三明治种类和对应的数量。 +因此,我们先用计数器 $cnt$ 统计学生喜欢的三明治种类和对应的数量。 -然后遍历三明治,若在 `cnt` 中找不到喜欢此三明治的学生,说明后面的三明治也无法被拿走,返回当前剩余的学生数量。 +然后遍历三明治,若在 $cnt$ 中找不到喜欢此三明治的学生,说明后面的三明治也无法被拿走,返回当前剩余的学生数量。 -遍历 +遍历结束。,说明所有学生都有三明治吃,返回 $0$。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为三明治数量。 +时间复杂度 $O(n)$,其中 $n$ 为三明治数量。空间复杂度 $O(1)$。 diff --git a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md index b2ab629f7074d..187d84453332f 100644 --- a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md +++ b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md @@ -54,6 +54,18 @@ Hence all students are able to eat. ## Solutions +**Solution 1: Counting** + +We observe that the positions of the students can be adjusted, but the positions of the sandwiches cannot be adjusted. That is to say, if the sandwich in front is not taken, then all the sandwiches behind cannot be taken. + +Therefore, we first use a counter $cnt$ to count the types of sandwiches that students like and their corresponding quantities. + +Then we traverse the sandwiches. If we cannot find a student who likes this sandwich in $cnt$, it means that the sandwiches behind cannot be taken, and we return the current number of remaining students. + +If the traversal is over, it means that all students have sandwiches to eat, and we return $0$. + +The time complexity is $O(n)$, where $n$ is the number of sandwiches. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1700-1799/1701.Average Waiting Time/README.md b/solution/1700-1799/1701.Average Waiting Time/README.md index 3ac16e422a1bd..c7c6d27c2c5c9 100644 --- a/solution/1700-1799/1701.Average Waiting Time/README.md +++ b/solution/1700-1799/1701.Average Waiting Time/README.md @@ -64,11 +64,11 @@ 遍历顾客数组 `customers`,对于每个顾客: -如果当前时间 `t` 小于等于顾客的到达时间 `customers[i][0]`,说明厨师没有在做菜,那么厨师可以立即开始做菜,做完这道菜的时间为 `t = customers[i][0] + customers[i][1]`,顾客的等待时间为 `customers[i][1]`。 +如果当前时间 `t` 小于等于顾客的到达时间 `customers[i][0]`,说明厨师没有在做菜,那么厨师可以立即开始做菜,做完这道菜的时间为 $t = customers[i][0] + customers[i][1]$,顾客的等待时间为 `customers[i][1]`。 -否则,说明厨师正在做菜,那么顾客需要等待厨师做完此前的菜,才能开始做自己的菜,做完这道菜的时间为 `t = t + customers[i][1]`,顾客的等待时间为 `t - customers[i][0]`。 +否则,说明厨师正在做菜,那么顾客需要等待厨师做完此前的菜,才能开始做自己的菜,做完这道菜的时间为 $t = t + customers[i][1]$,顾客的等待时间为 $t - customers[i][0]$。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为顾客数组 `customers` 的长度。 +时间复杂度 $O(n)$,其中 $n$ 为顾客数组 `customers` 的长度。空间复杂度 $O(1)$。 diff --git a/solution/1700-1799/1701.Average Waiting Time/README_EN.md b/solution/1700-1799/1701.Average Waiting Time/README_EN.md index 7501ea22b43c6..42fc8327724e6 100644 --- a/solution/1700-1799/1701.Average Waiting Time/README_EN.md +++ b/solution/1700-1799/1701.Average Waiting Time/README_EN.md @@ -52,6 +52,18 @@ So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. ## Solutions +**Solution 1: Simulation** + +We use a variable `tot` to record the total waiting time of the customers, and a variable `t` to record the time when each customer's order is completed. The initial values of both are $0$. + +We traverse the customer array `customers`. For each customer: + +If the current time `t` is less than or equal to the customer's arrival time `customers[i][0]`, it means that the chef is not cooking, so the chef can start cooking immediately. The time to complete this dish is $t = customers[i][0] + customers[i][1]$, and the customer's waiting time is `customers[i][1]`. + +Otherwise, it means that the chef is cooking, so the customer needs to wait for the chef to finish the previous dishes before starting to cook their own dishes. The time to complete this dish is $t = t + customers[i][1]$, and the customer's waiting time is $t - customers[i][0]$. + +The time complexity is $O(n)$, where $n$ is the length of the customer array `customers`. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1700-1799/1702.Maximum Binary String After Change/README.md b/solution/1700-1799/1702.Maximum Binary String After Change/README.md index d5a82ec6fde05..bcbf3be939470 100644 --- a/solution/1700-1799/1702.Maximum Binary String After Change/README.md +++ b/solution/1700-1799/1702.Maximum Binary String After Change/README.md @@ -65,7 +65,7 @@ 因此,要想得到最大的二进制串,我们应该把所有不在开头的 $1$ 移动到字符串末尾,使得字符串变为 `111..11...00..11` 的形式,然后借助操作 1 把中间的 `000..00` 变为 `111..10`。这样我们最终可以得到一个最多包含一个 $0$ 的二进制字符串,这个字符串就是我们要求的最大二进制串。 -时间复杂度 $O(n)$,忽略答案的空间消耗,空间复杂度 $O(1)$。其中 $n$ 为字符串 `binary` 的长度。 +时间复杂度 $O(n)$,其中 $n$ 为字符串 `binary` 的长度。忽略答案的空间消耗,空间复杂度 $O(1)$。 diff --git a/solution/1700-1799/1702.Maximum Binary String After Change/README_EN.md b/solution/1700-1799/1702.Maximum Binary String After Change/README_EN.md index fe69e79ff1131..6420fbabbf7a6 100644 --- a/solution/1700-1799/1702.Maximum Binary String After Change/README_EN.md +++ b/solution/1700-1799/1702.Maximum Binary String After Change/README_EN.md @@ -53,6 +53,14 @@ ## Solutions +**Solution 1: Quick Thinking** + +We observe that operation 2 can move all $1$s to the end of the string, and operation 1 can change all `0000..000` strings to `111..110`. + +Therefore, to get the maximum binary string, we should move all $1$s that are not at the beginning to the end of the string, making the string in the form of `111..11...00..11`, and then use operation 1 to change the middle `000..00` to `111..10`. In this way, we can finally get a binary string that contains at most one $0$, which is the maximum binary string we are looking for. + +The time complexity is $O(n)$, where $n$ is the length of the string `binary`. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README.md b/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README.md index e7305f0d93cee..e7ff6870f5b6b 100644 --- a/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README.md +++ b/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README.md @@ -49,13 +49,13 @@ **方法一:前缀和 + 中位数枚举** -我们可以将数组 `nums` 中的 `1` 的下标存入数组 `arr` 中。接下来,我们预处理数组 `arr` 的前缀和数组 `s`,其中 `s[i]` 表示数组 `arr` 中前 $i$ 个元素的和。 +我们可以将数组 $nums$ 中的 $1$ 的下标存入数组 $arr$ 中。接下来,我们预处理数组 $arr$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $arr$ 中前 $i$ 个元素的和。 对于长度为 $k$ 的子数组,左侧(包含中位数)的元素个数 $x=\frac{k+1}{2}$,右侧的元素个数为 $y=k-x$。 -我们枚举中位数的下标 $i$,其中 $x-1\leq i\leq len(arr)-y$,那么左侧数组的前缀和 $ls=s[i+1]-s[i+1-x]$,右侧数组的前缀和 $rs=s[i+1+y]-s[i+1]$。当前中位数在 `nums` 中的下标为 $j=arr[i]$,将左侧 $x$ 个元素移动到 $[j-x+1,..j]$ 所需要的操作次数为 $a=(j+j-x+1)\times\frac{x}{2}-ls$,将右侧 $y$ 个元素移动到 $[j+1,..j+y]$ 所需要的操作次数为 $b=rs-(j+1+j+y)\times\frac{y}{2}$,那么总的操作次数为 $a+b$,我们取所有总的操作次数的最小值即可。 +我们枚举中位数的下标 $i$,其中 $x-1\leq i\leq len(arr)-y$,那么左侧数组的前缀和 $ls=s[i+1]-s[i+1-x]$,右侧数组的前缀和 $rs=s[i+1+y]-s[i+1]$。当前中位数在 $nums$ 中的下标为 $j=arr[i]$,将左侧 $x$ 个元素移动到 $[j-x+1,..j]$ 所需要的操作次数为 $a=(j+j-x+1)\times\frac{x}{2}-ls$,将右侧 $y$ 个元素移动到 $[j+1,..j+y]$ 所需要的操作次数为 $b=rs-(j+1+j+y)\times\frac{y}{2}$,那么总的操作次数为 $a+b$,我们取所有总的操作次数的最小值即可。 -时间复杂度 $O(n)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为数组 `nums` 的长度以及数组 `nums` 中 `1` 的个数。 +时间复杂度 $O(n)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为数组 $nums$ 的长度以及数组 $nums$ 中 $1$ 的个数。 diff --git a/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md b/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md index aa408a7c4ac46..1f4d8e981281c 100644 --- a/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md +++ b/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md @@ -44,6 +44,16 @@ ## Solutions +**Solution 1: Prefix Sum + Median Enumeration** + +We can store the indices of $1$s in the array $nums$ into an array $arr$. Next, we preprocess the prefix sum array $s$ of the array $arr$, where $s[i]$ represents the sum of the first $i$ elements in the array $arr$. + +For a subarray of length $k$, the number of elements on the left (including the median) is $x=\frac{k+1}{2}$, and the number of elements on the right is $y=k-x$. + +We enumerate the index $i$ of the median, where $x-1\leq i\leq len(arr)-y$. The prefix sum of the left array is $ls=s[i+1]-s[i+1-x]$, and the prefix sum of the right array is $rs=s[i+1+y]-s[i+1]$. The current median index in $nums$ is $j=arr[i]$. The number of operations required to move the left $x$ elements to $[j-x+1,..j]$ is $a=(j+j-x+1)\times\frac{x}{2}-ls$, and the number of operations required to move the right $y$ elements to $[j+1,..j+y]$ is $b=rs-(j+1+j+y)\times\frac{y}{2}$. The total number of operations is $a+b$, and we take the minimum of all total operation counts. + +The time complexity is $O(n)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the length of the array $nums$ and the number of $1$s in the array $nums$, respectively. + ### **Python3** diff --git a/solution/1700-1799/1704.Determine if String Halves Are Alike/README.md b/solution/1700-1799/1704.Determine if String Halves Are Alike/README.md index 9e23c1c70a8bf..47d29a1e1fa28 100644 --- a/solution/1700-1799/1704.Determine if String Halves Are Alike/README.md +++ b/solution/1700-1799/1704.Determine if String Halves Are Alike/README.md @@ -49,7 +49,7 @@ 遍历字符串,若字符串前半段的元音个数等于后半段的元音个数,则返回 `true`,否则返回 `false`。 -时间复杂度 $O(n)$,其中 $n$ 为字符串的长度。 +时间复杂度 $O(n)$,其中 $n$ 为字符串的长度。空间复杂度 $O(C)$,其中 $C$ 为元音字母的个数。 diff --git a/solution/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md b/solution/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md index 9e92c178593dc..9af178b3e83a4 100644 --- a/solution/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md +++ b/solution/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md @@ -39,6 +39,12 @@ Notice that the vowel o is counted twice. ## Solutions +**Solution 1: Counting** + +Traverse the string. If the number of vowels in the first half of the string is equal to the number of vowels in the second half, return `true`. Otherwise, return `false`. + +The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(C)$, where $C$ is the number of vowel characters. + ### **Python3** diff --git a/solution/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md b/solution/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md index e91ef1c69c9e5..c9564d53c0b3d 100644 --- a/solution/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md +++ b/solution/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md @@ -46,6 +46,14 @@ ## Solutions +**Solution 1: Greedy + Priority Queue** + +We can greedily choose the apple that is most likely to rot among the unrotten apples, so that we can eat as many apples as possible. + +Therefore, we can use a priority queue (min heap) to store the rotting time of the apples and the corresponding number of apples. Each time we take out the apple with the smallest rotting time from the priority queue, then reduce its quantity by one. If the quantity of the apple is not zero after reduction, we put it back into the priority queue. If the apple has rotted, we pop it out from the priority queue. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `apples` or `days`. + ### **Python3**