diff --git a/solution/2000-2099/2000.Reverse Prefix of Word/README_EN.md b/solution/2000-2099/2000.Reverse Prefix of Word/README_EN.md index 0ed57743123e1..c13eab2cb0ac4 100644 --- a/solution/2000-2099/2000.Reverse Prefix of Word/README_EN.md +++ b/solution/2000-2099/2000.Reverse Prefix of Word/README_EN.md @@ -51,6 +51,12 @@ You should not do any reverse operation, the resulting string is "abcd" ## Solutions +**Solution 1: Simulation** + +First, we find the index $i$ where the character $ch$ first appears. Then, we reverse the characters from index $0$ to index $i$ (including index $i$). Finally, we concatenate the reversed string with the string starting from index $i + 1$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $word$. + ### **Python3** diff --git a/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README.md b/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README.md index 20068e6d2c4d5..667dec5bda68b 100644 --- a/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README.md +++ b/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README.md @@ -55,7 +55,7 @@ 为了能够唯一表示矩形,我们需要将矩形的宽高比化简为最简分数。因此,我们可以求出每个矩形的宽高比的最大公约数,然后将宽高比化简为最简分数。接下来,我们使用哈希表统计每个最简分数的矩形数量,然后计算每个最简分数的矩形数量的组合数,即可得到答案。 -时间复杂度 $O(n \log M)$,空间复杂度 $O(n)$。其中 $n$ 和 $M$ 分别是矩形的数量和矩形的最大边长。 +时间复杂度 $O(n \times \log M)$,空间复杂度 $O(n)$。其中 $n$ 和 $M$ 分别是矩形的数量和矩形的最大边长。 diff --git a/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README_EN.md b/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README_EN.md index b9db20533064b..972c1a1f4ed96 100644 --- a/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README_EN.md +++ b/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README_EN.md @@ -45,6 +45,12 @@ ## Solutions +**Solution 1: Mathematics + Hash Table** + +In order to uniquely represent a rectangle, we need to simplify the width-to-height ratio of the rectangle to a simplest fraction. Therefore, we can find the greatest common divisor of the width-to-height ratio of each rectangle, and then simplify the width-to-height ratio to the simplest fraction. Next, we use a hash table to count the number of rectangles for each simplest fraction, and then calculate the combination of the number of rectangles for each simplest fraction to get the answer. + +The time complexity is $O(n \times \log M)$, and the space complexity is $O(n)$. Here, $n$ and $M$ are the number of rectangles and the maximum side length of the rectangles, respectively. + ### **Python3** diff --git a/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README_EN.md b/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README_EN.md index 66a2b4abbee23..c2383c0890906 100644 --- a/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README_EN.md +++ b/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README_EN.md @@ -48,6 +48,14 @@ The product of their lengths is: 5 * 5 = 25. ## Solutions +**Solution 1: Binary Enumeration** + +We notice that the length of the string $s$ does not exceed $12$, so we can use the method of binary enumeration to enumerate all subsequences of $s$. Suppose the length of $s$ is $n$, we can use $2^n$ binary numbers of length $n$ to represent all subsequences of $s$. For each binary number, the $i$-th bit being $1$ means the $i$-th character of $s$ is in the subsequence, and $0$ means it is not in the subsequence. For each binary number, we judge whether it is a palindrome subsequence and record it in the array $p$. + +Next, we enumerate each number $i$ in $p$. If $i$ is a palindrome subsequence, then we can enumerate a number $j$ from the complement of $i$, $mx = (2^n - 1) \oplus i$. If $j$ is also a palindrome subsequence, then $i$ and $j$ are the two palindrome subsequences we are looking for. Their lengths are the number of $1$s in the binary representation of $i$ and $j$, denoted as $a$ and $b$, respectively. Then their product is $a \times b$. We take the maximum of all possible $a \times b$. + +The time complexity is $(2^n \times n + 3^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the length of the string $s$. + ### **Python3** diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README.md b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README.md index 99fa51b0d2a1d..69a90157d713d 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README.md +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README.md @@ -61,19 +61,19 @@ **方法一:暴力枚举** -我们注意到,数组 `nums` 的长度不超过 $200$,因此我们可以枚举所有的数对 $(i, j)$,其中 $i < j$,并判断 $|nums[i] - nums[j]|$ 是否等于 $k$,是则答案加一。 +我们注意到,数组 $nums$ 的长度不超过 $200$,因此我们可以枚举所有的数对 $(i, j)$,其中 $i < j$,并判断 $|nums[i] - nums[j]|$ 是否等于 $k$,是则答案加一。 最后返回答案即可。 -时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 **方法二:哈希表或数组** -我们可以使用哈希表或数组记录数组 `nums` 中每个数出现的次数,然后枚举数组 `nums` 中的每个数 $x$,判断 $x + k$ 和 $x - k$ 是否在数组 `nums` 中,是则答案加上 $x+k$ 和 $x-k$ 出现的次数之和。 +我们可以使用哈希表或数组记录数组 $nums$ 中每个数出现的次数,然后枚举数组 $nums$ 中的每个数 $x$,判断 $x + k$ 和 $x - k$ 是否在数组 $nums$ 中,是则答案加上 $x+k$ 和 $x-k$ 出现的次数之和。 最后返回答案即可。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README_EN.md b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README_EN.md index 250117a66977a..e8c6442012b0e 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README_EN.md +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README_EN.md @@ -56,6 +56,22 @@ ## Solutions +**Solution 1: Brute Force Enumeration** + +We notice that the length of the array $nums$ does not exceed $200$, so we can enumerate all pairs $(i, j)$, where $i < j$, and check if $|nums[i] - nums[j]|$ equals $k$. If it does, we increment the answer by one. + +Finally, we return the answer. + +The time complexity is $O(n^2)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. + +**Solution 2: Hash Table or Array** + +We can use a hash table or array to record the occurrence count of each number in the array $nums$. Then, we enumerate each number $x$ in the array $nums$, and check if $x + k$ and $x - k$ are in the array $nums$. If they are, we increment the answer by the sum of the occurrence counts of $x + k$ and $x - k$. + +Finally, we return the answer. + +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/2000-2099/2007.Find Original Array From Doubled Array/README_EN.md b/solution/2000-2099/2007.Find Original Array From Doubled Array/README_EN.md index c63ead95620e2..0df1b54ba8d62 100644 --- a/solution/2000-2099/2007.Find Original Array From Doubled Array/README_EN.md +++ b/solution/2000-2099/2007.Find Original Array From Doubled Array/README_EN.md @@ -47,6 +47,18 @@ Other original arrays could be [4,3,1] or [3,1,4]. ## Solutions +**Solution 1: Sorting + Counting + Traversal** + +First, we check if the length $n$ of the array `changed` is odd. If it is, we directly return an empty array. + +Then, we sort the array `changed`, and use a hash table or array `cnt` to count the occurrence of each element in `changed`. + +Next, we traverse the array `changed`. For each element $x$ in `changed`, we first check if $x$ exists in the hash table `cnt`. If it does not exist, we directly skip this element. Otherwise, we check if $x \times 2$ exists in `cnt`. If it does not exist, we directly return an empty array. Otherwise, we add $x$ to the answer array `ans`, and decrease the occurrence counts of $x$ and $x \times 2$ in `cnt` by $1$ each. + +After the traversal, we check if the length of the answer array `ans` is $\frac{n}{2}$. If it is, we return `ans`, otherwise we return an empty array. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `changed`. + ### **Python3** diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md index 359e49b92443b..f8bb443093238 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md @@ -57,6 +57,26 @@ The resulting array is [1,2,3,4], which is continuous. ## Solutions +**Solution 1: Sorting + Deduplication + Binary Search** + +First, we sort the array and remove duplicates. + +Then, we traverse the array, enumerating the current element $nums[i]$ as the minimum value of the consecutive array. We use binary search to find the first position $j$ that is greater than $nums[i] + n - 1$. Then, $j-i$ is the length of the consecutive array when the current element is the minimum value. We update the answer, i.e., $ans = \min(ans, n - (j - i))$. + +Finally, we return $ans$. + +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. + +**Solution 2: Sorting + Deduplication + Two Pointers** + +Similar to Solution 1, we first sort the array and remove duplicates. + +Then, we traverse the array, enumerating the current element $nums[i]$ as the minimum value of the consecutive array. We use two pointers to find the first position $j$ that is greater than $nums[i] + n - 1$. Then, $j-i$ is the length of the consecutive array when the current element is the minimum value. We update the answer, i.e., $ans = \min(ans, n - (j - i))$. + +Finally, we return $ans$. + +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/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README.md b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README.md index c720e3d19c01e..7597cafb11fa8 100644 --- a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README.md +++ b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README.md @@ -73,7 +73,7 @@ X--:X 减 1 ,X = 1 - 1 = 0 遍历数组 `operations`,对于每个操作 $operations[i]$,如果包含 `'+'`,那么答案加 $1$,否则答案减 $1$。 -时间复杂度为 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `operations` 的长度。 +时间复杂度为 $O(n)$,其中 $n$ 为数组 `operations` 的长度。空间复杂度 $O(1)$。 diff --git a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README_EN.md b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README_EN.md index d6aa081a7d467..24db735dcb32e 100644 --- a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README_EN.md +++ b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README_EN.md @@ -63,6 +63,12 @@ X--: X is decremented by 1, X = 1 - 1 = 0. ## Solutions +**Solution 1: Simulation** + +Traverse the array `operations`. For each operation $operations[i]$, if it contains `'+'`, then the answer increases by $1$, otherwise the answer decreases by $1$. + +The time complexity is $O(n)$, where $n$ is the length of the array `operations`. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/README.md b/solution/2000-2099/2012.Sum of Beauty in the Array/README.md index 373e7a6ed7923..dca2030754e2f 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/README.md +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/README.md @@ -56,6 +56,16 @@ +**方法一:预处理右侧最小值 + 遍历维护左侧最大值** + +我们可以预处理出右侧最小值数组 $right$,其中 $right[i]$ 表示 $nums[i..n-1]$ 中的最小值。 + +然后我们从左到右遍历数组 $nums$,同时维护左侧最大值 $l$。对于每个位置 $i$,我们判断 $l < nums[i] < right[i + 1]$ 是否成立,如果成立则将 $2$ 累加至答案,否则判断 $nums[i - 1] < nums[i] < nums[i + 1]$ 是否成立,如果成立则将 $1$ 累加至答案。 + +遍历结束后即可得到答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 + ### **Python3** @@ -66,18 +76,18 @@ class Solution: def sumOfBeauties(self, nums: List[int]) -> int: n = len(nums) - lmx = [0] * n - for i in range(1, n): - lmx[i] = max(lmx[i - 1], nums[i - 1]) - rmi = [100001] * n + right = [nums[-1]] * n for i in range(n - 2, -1, -1): - rmi[i] = min(rmi[i + 1], nums[i + 1]) + right[i] = min(right[i + 1], nums[i]) ans = 0 + l = nums[0] for i in range(1, n - 1): - if lmx[i] < nums[i] < rmi[i]: + r = right[i + 1] + if l < nums[i] < r: ans += 2 elif nums[i - 1] < nums[i] < nums[i + 1]: ans += 1 + l = max(l, nums[i]) return ans ``` @@ -89,53 +99,27 @@ class Solution: class Solution { public int sumOfBeauties(int[] nums) { int n = nums.length; - int[] lmx = new int[n]; - int[] rmi = new int[n]; - rmi[n - 1] = 100001; - for (int i = 1; i < n; ++i) { - lmx[i] = Math.max(lmx[i - 1], nums[i - 1]); - } - for (int i = n - 2; i >= 0; --i) { - rmi[i] = Math.min(rmi[i + 1], nums[i + 1]); + int[] right = new int[n]; + right[n - 1] = nums[n - 1]; + for (int i = n - 2; i > 0; --i) { + right[i] = Math.min(right[i + 1], nums[i]); } int ans = 0; + int l = nums[0]; for (int i = 1; i < n - 1; ++i) { - if (lmx[i] < nums[i] && nums[i] < rmi[i]) { + int r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { ans += 2; } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { ans += 1; } + l = Math.max(l, nums[i]); } return ans; } } ``` -### \*\*TypeScript - -```ts -function sumOfBeauties(nums: number[]): number { - let n = nums.length; - let prefix = new Array(n), - postfix = new Array(n); - prefix[0] = nums[0]; - postfix[n - 1] = nums[n - 1]; - for (let i = 1, j = n - 2; i < n; ++i, --j) { - prefix[i] = Math.max(nums[i], prefix[i - 1]); - postfix[j] = Math.min(nums[j], postfix[j + 1]); - } - let ans = 0; - for (let i = 1; i < n - 1; ++i) { - if (prefix[i - 1] < nums[i] && nums[i] < postfix[i + 1]) { - ans += 2; - } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { - ans += 1; - } - } - return ans; -} -``` - ### **C++** ```cpp @@ -143,16 +127,19 @@ class Solution { public: int sumOfBeauties(vector& nums) { int n = nums.size(); - vector lmx(n); - vector rmi(n, 100001); - for (int i = 1; i < n; ++i) lmx[i] = max(lmx[i - 1], nums[i - 1]); - for (int i = n - 2; i >= 0; --i) rmi[i] = min(rmi[i + 1], nums[i + 1]); + vector right(n, nums[n - 1]); + for (int i = n - 2; i; --i) { + right[i] = min(right[i + 1], nums[i]); + } int ans = 0; - for (int i = 1; i < n - 1; ++i) { - if (lmx[i] < nums[i] && nums[i] < rmi[i]) + for (int i = 1, l = nums[0]; i < n - 1; ++i) { + int r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { ans += 2; - else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { ans += 1; + } + l = max(l, nums[i]); } return ans; } @@ -162,26 +149,46 @@ public: ### **Go** ```go -func sumOfBeauties(nums []int) int { +func sumOfBeauties(nums []int) (ans int) { n := len(nums) - lmx := make([]int, n) - rmi := make([]int, n) - rmi[n-1] = 100001 - for i := 1; i < n; i++ { - lmx[i] = max(lmx[i-1], nums[i-1]) - } - for i := n - 2; i >= 0; i-- { - rmi[i] = min(rmi[i+1], nums[i+1]) + right := make([]int, n) + right[n-1] = nums[n-1] + for i := n - 2; i > 0; i-- { + right[i] = min(right[i+1], nums[i]) } - ans := 0 - for i := 1; i < n-1; i++ { - if lmx[i] < nums[i] && nums[i] < rmi[i] { + for i, l := 1, nums[0]; i < n-1; i++ { + r := right[i+1] + if l < nums[i] && nums[i] < r { ans += 2 } else if nums[i-1] < nums[i] && nums[i] < nums[i+1] { - ans += 1 + ans++ } + l = max(l, nums[i]) } - return ans + return +} +``` + +### **TypeScript** + +```ts +function sumOfBeauties(nums: number[]): number { + const n = nums.length; + const right: number[] = Array(n).fill(nums[n - 1]); + for (let i = n - 2; i; --i) { + right[i] = Math.min(right[i + 1], nums[i]); + } + let ans = 0; + for (let i = 1, l = nums[0]; i < n - 1; ++i) { + const r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { + ans += 2; + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { + ans += 1; + } + l = Math.max(l, nums[i]); + } + return ans; } ``` diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/README_EN.md b/solution/2000-2099/2012.Sum of Beauty in the Array/README_EN.md index f50ded9a1a124..53d91ccb0eb9a 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/README_EN.md +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/README_EN.md @@ -53,6 +53,16 @@ ## Solutions +**Solution 1: Preprocessing Right Minimum + Traversing to Maintain Left Maximum** + +We can preprocess the right minimum array $right$, where $right[i]$ represents the minimum value in $nums[i..n-1]$. + +Then we traverse the array $nums$ from left to right, while maintaining the maximum value $l$ on the left. For each position $i$, we judge whether $l < nums[i] < right[i + 1]$ holds. If it does, we add $2$ to the answer. Otherwise, we judge whether $nums[i - 1] < nums[i] < nums[i + 1]$ holds. If it does, we add $1$ to the answer. + +After the traversal, we can get the answer. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + ### **Python3** @@ -61,18 +71,18 @@ class Solution: def sumOfBeauties(self, nums: List[int]) -> int: n = len(nums) - lmx = [0] * n - for i in range(1, n): - lmx[i] = max(lmx[i - 1], nums[i - 1]) - rmi = [100001] * n + right = [nums[-1]] * n for i in range(n - 2, -1, -1): - rmi[i] = min(rmi[i + 1], nums[i + 1]) + right[i] = min(right[i + 1], nums[i]) ans = 0 + l = nums[0] for i in range(1, n - 1): - if lmx[i] < nums[i] < rmi[i]: + r = right[i + 1] + if l < nums[i] < r: ans += 2 elif nums[i - 1] < nums[i] < nums[i + 1]: ans += 1 + l = max(l, nums[i]) return ans ``` @@ -82,53 +92,27 @@ class Solution: class Solution { public int sumOfBeauties(int[] nums) { int n = nums.length; - int[] lmx = new int[n]; - int[] rmi = new int[n]; - rmi[n - 1] = 100001; - for (int i = 1; i < n; ++i) { - lmx[i] = Math.max(lmx[i - 1], nums[i - 1]); - } - for (int i = n - 2; i >= 0; --i) { - rmi[i] = Math.min(rmi[i + 1], nums[i + 1]); + int[] right = new int[n]; + right[n - 1] = nums[n - 1]; + for (int i = n - 2; i > 0; --i) { + right[i] = Math.min(right[i + 1], nums[i]); } int ans = 0; + int l = nums[0]; for (int i = 1; i < n - 1; ++i) { - if (lmx[i] < nums[i] && nums[i] < rmi[i]) { + int r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { ans += 2; } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { ans += 1; } + l = Math.max(l, nums[i]); } return ans; } } ``` -### **TypeScript** - -```ts -function sumOfBeauties(nums: number[]): number { - let n = nums.length; - let prefix = new Array(n), - postfix = new Array(n); - prefix[0] = nums[0]; - postfix[n - 1] = nums[n - 1]; - for (let i = 1, j = n - 2; i < n; ++i, --j) { - prefix[i] = Math.max(nums[i], prefix[i - 1]); - postfix[j] = Math.min(nums[j], postfix[j + 1]); - } - let ans = 0; - for (let i = 1; i < n - 1; ++i) { - if (prefix[i - 1] < nums[i] && nums[i] < postfix[i + 1]) { - ans += 2; - } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { - ans += 1; - } - } - return ans; -} -``` - ### **C++** ```cpp @@ -136,16 +120,19 @@ class Solution { public: int sumOfBeauties(vector& nums) { int n = nums.size(); - vector lmx(n); - vector rmi(n, 100001); - for (int i = 1; i < n; ++i) lmx[i] = max(lmx[i - 1], nums[i - 1]); - for (int i = n - 2; i >= 0; --i) rmi[i] = min(rmi[i + 1], nums[i + 1]); + vector right(n, nums[n - 1]); + for (int i = n - 2; i; --i) { + right[i] = min(right[i + 1], nums[i]); + } int ans = 0; - for (int i = 1; i < n - 1; ++i) { - if (lmx[i] < nums[i] && nums[i] < rmi[i]) + for (int i = 1, l = nums[0]; i < n - 1; ++i) { + int r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { ans += 2; - else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { ans += 1; + } + l = max(l, nums[i]); } return ans; } @@ -155,26 +142,46 @@ public: ### **Go** ```go -func sumOfBeauties(nums []int) int { +func sumOfBeauties(nums []int) (ans int) { n := len(nums) - lmx := make([]int, n) - rmi := make([]int, n) - rmi[n-1] = 100001 - for i := 1; i < n; i++ { - lmx[i] = max(lmx[i-1], nums[i-1]) - } - for i := n - 2; i >= 0; i-- { - rmi[i] = min(rmi[i+1], nums[i+1]) + right := make([]int, n) + right[n-1] = nums[n-1] + for i := n - 2; i > 0; i-- { + right[i] = min(right[i+1], nums[i]) } - ans := 0 - for i := 1; i < n-1; i++ { - if lmx[i] < nums[i] && nums[i] < rmi[i] { + for i, l := 1, nums[0]; i < n-1; i++ { + r := right[i+1] + if l < nums[i] && nums[i] < r { ans += 2 } else if nums[i-1] < nums[i] && nums[i] < nums[i+1] { - ans += 1 + ans++ } + l = max(l, nums[i]) } - return ans + return +} +``` + +### **TypeScript** + +```ts +function sumOfBeauties(nums: number[]): number { + const n = nums.length; + const right: number[] = Array(n).fill(nums[n - 1]); + for (let i = n - 2; i; --i) { + right[i] = Math.min(right[i + 1], nums[i]); + } + let ans = 0; + for (let i = 1, l = nums[0]; i < n - 1; ++i) { + const r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { + ans += 2; + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { + ans += 1; + } + l = Math.max(l, nums[i]); + } + return ans; } ``` diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.cpp b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.cpp index db2f340c793c3..7089561bf76bb 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.cpp +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.cpp @@ -1,18 +1,21 @@ -class Solution { -public: - int sumOfBeauties(vector& nums) { - int n = nums.size(); - vector lmx(n); - vector rmi(n, 100001); - for (int i = 1; i < n; ++i) lmx[i] = max(lmx[i - 1], nums[i - 1]); - for (int i = n - 2; i >= 0; --i) rmi[i] = min(rmi[i + 1], nums[i + 1]); - int ans = 0; - for (int i = 1; i < n - 1; ++i) { - if (lmx[i] < nums[i] && nums[i] < rmi[i]) - ans += 2; - else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) - ans += 1; - } - return ans; - } +class Solution { +public: + int sumOfBeauties(vector& nums) { + int n = nums.size(); + vector right(n, nums[n - 1]); + for (int i = n - 2; i; --i) { + right[i] = min(right[i + 1], nums[i]); + } + int ans = 0; + for (int i = 1, l = nums[0]; i < n - 1; ++i) { + int r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { + ans += 2; + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { + ans += 1; + } + l = max(l, nums[i]); + } + return ans; + } }; \ No newline at end of file diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.go b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.go index eca8aae4425c8..a8b52d6ef1a21 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.go +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.go @@ -1,21 +1,18 @@ -func sumOfBeauties(nums []int) int { +func sumOfBeauties(nums []int) (ans int) { n := len(nums) - lmx := make([]int, n) - rmi := make([]int, n) - rmi[n-1] = 100001 - for i := 1; i < n; i++ { - lmx[i] = max(lmx[i-1], nums[i-1]) + right := make([]int, n) + right[n-1] = nums[n-1] + for i := n - 2; i > 0; i-- { + right[i] = min(right[i+1], nums[i]) } - for i := n - 2; i >= 0; i-- { - rmi[i] = min(rmi[i+1], nums[i+1]) - } - ans := 0 - for i := 1; i < n-1; i++ { - if lmx[i] < nums[i] && nums[i] < rmi[i] { + for i, l := 1, nums[0]; i < n-1; i++ { + r := right[i+1] + if l < nums[i] && nums[i] < r { ans += 2 } else if nums[i-1] < nums[i] && nums[i] < nums[i+1] { - ans += 1 + ans++ } + l = max(l, nums[i]) } - return ans + return } \ No newline at end of file diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.java b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.java index c219e40f0abe2..fec95d8691258 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.java +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.java @@ -1,23 +1,22 @@ -class Solution { - public int sumOfBeauties(int[] nums) { - int n = nums.length; - int[] lmx = new int[n]; - int[] rmi = new int[n]; - rmi[n - 1] = 100001; - for (int i = 1; i < n; ++i) { - lmx[i] = Math.max(lmx[i - 1], nums[i - 1]); - } - for (int i = n - 2; i >= 0; --i) { - rmi[i] = Math.min(rmi[i + 1], nums[i + 1]); - } - int ans = 0; - for (int i = 1; i < n - 1; ++i) { - if (lmx[i] < nums[i] && nums[i] < rmi[i]) { - ans += 2; - } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { - ans += 1; - } - } - return ans; - } +class Solution { + public int sumOfBeauties(int[] nums) { + int n = nums.length; + int[] right = new int[n]; + right[n - 1] = nums[n - 1]; + for (int i = n - 2; i > 0; --i) { + right[i] = Math.min(right[i + 1], nums[i]); + } + int ans = 0; + int l = nums[0]; + for (int i = 1; i < n - 1; ++i) { + int r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { + ans += 2; + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { + ans += 1; + } + l = Math.max(l, nums[i]); + } + return ans; + } } \ No newline at end of file diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.py b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.py index c6f6f2a51b220..f462ac563ccca 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.py +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.py @@ -1,16 +1,16 @@ -class Solution: - def sumOfBeauties(self, nums: List[int]) -> int: - n = len(nums) - lmx = [0] * n - for i in range(1, n): - lmx[i] = max(lmx[i - 1], nums[i - 1]) - rmi = [100001] * n - for i in range(n - 2, -1, -1): - rmi[i] = min(rmi[i + 1], nums[i + 1]) - ans = 0 - for i in range(1, n - 1): - if lmx[i] < nums[i] < rmi[i]: - ans += 2 - elif nums[i - 1] < nums[i] < nums[i + 1]: - ans += 1 - return ans +class Solution: + def sumOfBeauties(self, nums: List[int]) -> int: + n = len(nums) + right = [nums[-1]] * n + for i in range(n - 2, -1, -1): + right[i] = min(right[i + 1], nums[i]) + ans = 0 + l = nums[0] + for i in range(1, n - 1): + r = right[i + 1] + if l < nums[i] < r: + ans += 2 + elif nums[i - 1] < nums[i] < nums[i + 1]: + ans += 1 + l = max(l, nums[i]) + return ans diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.ts b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.ts index a80fab7671f33..5e4a88c3e54ec 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.ts +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/Solution.ts @@ -1,20 +1,18 @@ function sumOfBeauties(nums: number[]): number { - let n = nums.length; - let prefix = new Array(n), - postfix = new Array(n); - prefix[0] = nums[0]; - postfix[n - 1] = nums[n - 1]; - for (let i = 1, j = n - 2; i < n; ++i, --j) { - prefix[i] = Math.max(nums[i], prefix[i - 1]); - postfix[j] = Math.min(nums[j], postfix[j + 1]); + const n = nums.length; + const right: number[] = Array(n).fill(nums[n - 1]); + for (let i = n - 2; i; --i) { + right[i] = Math.min(right[i + 1], nums[i]); } let ans = 0; - for (let i = 1; i < n - 1; ++i) { - if (prefix[i - 1] < nums[i] && nums[i] < postfix[i + 1]) { + for (let i = 1, l = nums[0]; i < n - 1; ++i) { + const r = right[i + 1]; + if (l < nums[i] && nums[i] < r) { ans += 2; } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { ans += 1; } + l = Math.max(l, nums[i]); } return ans; } diff --git a/solution/2000-2099/2013.Detect Squares/README_EN.md b/solution/2000-2099/2013.Detect Squares/README_EN.md index d435b3f3f0a42..6b5f329bbfeed 100644 --- a/solution/2000-2099/2013.Detect Squares/README_EN.md +++ b/solution/2000-2099/2013.Detect Squares/README_EN.md @@ -57,6 +57,16 @@ detectSquares.count([11, 10]); // return 2. You can choose: ## Solutions +**Solution 1: Hash Table** + +We can use a hash table $cnt$ to maintain all the information of the points, where $cnt[x][y]$ represents the count of point $(x, y)$. + +When calling the $add(x, y)$ method, we increase the value of $cnt[x][y]$ by $1$. + +When calling the $count(x_1, y_1)$ method, we need to get three other points to form an axis-aligned square. We can enumerate the point $(x_2, y_1)$ that is parallel to the $x$-axis and at a distance $d$ from $(x_1, y_1)$. If such a point exists, based on these two points, we can determine the other two points as $(x_1, y_1 + d)$ and $(x_2, y_1 + d)$, or $(x_1, y_1 - d)$ and $(x_2, y_1 - d)$. We can add up the number of schemes for these two situations. + +In terms of time complexity, the time complexity of calling the $add(x, y)$ method is $O(1)$, and the time complexity of calling the $count(x_1, y_1)$ method is $O(n)$; the space complexity is $O(n)$. Here, $n$ is the number of points in the data stream. + ### **Python3** diff --git a/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README.md b/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README.md index 8c1d57c0aa5e8..7c0888a757553 100644 --- a/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README.md +++ b/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README.md @@ -11,14 +11,12 @@
  • 例如,如果 buildings = [[1,5,2],[3,10,4]] , street = [[1,3,2],[3,5,3],[5,10,4]] 可以表示街道,因为: -
    • 从 1 到 3 ,只有第一栋建筑的平均高度为 2 / 1 = 2
    • 从 3 到 5 ,第一和第二栋建筑的平均高度均为 (2+4) / 2 = 3
    • 从 5 到 10 ,只有第二栋建筑的平均高度为 4 / 1 = 4
  • -

给定 buildings ,返回如上所述的二维整数矩阵 street 不包括 街道上没有建筑物的任何区域)。您可以按 任何顺序 返回数组。
@@ -85,7 +83,7 @@ 最后遍历有序哈希表,对于每个位置,如果高度和建筑物数量都不为 0,则说明该位置有建筑物,判断此时的建筑物是否与上个建筑物的平均高度相同,如果相同,则合并,否则加入结果集。 -时间复杂度为 $O(n\log n)$,其中 $n$ 为建筑物数量。 +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为建筑物数量。 diff --git a/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README_EN.md b/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README_EN.md index 9d77361e7958e..04440f70dbfc1 100644 --- a/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README_EN.md +++ b/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README_EN.md @@ -10,14 +10,12 @@

  • For example, if buildings = [[1,5,2],[3,10,4]], the street could be represented by street = [[1,3,2],[3,5,3],[5,10,4]] because: -
    • From 1 to 3, there is only the first building with an average height of 2 / 1 = 2.
    • From 3 to 5, both the first and the second building are there with an average height of (2+4) / 2 = 3.
    • From 5 to 10, there is only the second building with an average height of 4 / 1 = 4.
  • -

Given buildings, return the 2D integer array street as described above (excluding any areas of the street where there are no buldings). You may return the array in any order.

@@ -76,6 +74,14 @@ We cannot group the segments together because an empty space with no buildings s ## Solutions +**Solution 1: Differential Ordered Hash Table** + +We use the differential idea and an ordered hash table `height` to record the height change at each position, and `cnt` to record the change in the number of buildings. By calculating the prefix sum of the ordered hash table, we can get the height and the number of buildings at each position. + +Finally, we traverse the ordered hash table. For each position, if both the height and the number of buildings are not zero, it means that there is a building at this position. We then check whether the average height of the building at this time is the same as that of the previous building. If it is the same, we merge them; otherwise, we add it to the result set. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of buildings. + ### **Python3** diff --git a/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README.md b/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README.md index c4516dd1e8905..f24db30adee2a 100644 --- a/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README.md +++ b/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README.md @@ -59,7 +59,7 @@ 遍历结束后,返回 $ans$。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。 +时间复杂度 $O(n)$,其中 $n$ 为数组的长度。空间复杂度 $O(1)$。 diff --git a/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README_EN.md b/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README_EN.md index 1cc4bbde86caa..6218fd05f2301 100644 --- a/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README_EN.md +++ b/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README_EN.md @@ -48,6 +48,16 @@ The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = ## Solutions +**Solution 1: Maintaining Prefix Minimum** + +We use the variable $mi$ to represent the minimum value of the elements we have traversed so far, and the variable $ans$ to represent the maximum difference. Initially, $mi$ is set to $+\infty$, and $ans$ is set to $-1$. + +We traverse the array. For the current element $x$, if $x > mi$, then we update $ans$ to be $max(ans, x - mi)$, otherwise we update $mi = x$. + +After the traversal, we return $ans$. + +The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/2000-2099/2017.Grid Game/README_EN.md b/solution/2000-2099/2017.Grid Game/README_EN.md index 2ca506dff5f7d..691e58097240d 100644 --- a/solution/2000-2099/2017.Grid Game/README_EN.md +++ b/solution/2000-2099/2017.Grid Game/README_EN.md @@ -55,6 +55,18 @@ The second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points. ## Solutions +**Solution 1: Prefix Sum** + +We notice that if we determine the position $j$ where the first robot turns down, then the optimal path of the second robot is also determined. The optimal path of the second robot is the prefix sum of the first row from $j+1$ to $n-1$, or the prefix sum of the second row from $0$ to $j-1$, taking the maximum of the two. + +First, we calculate the suffix sum of the points in the first row, denoted as $s_1$, and the prefix sum of the points in the second row, denoted as $s_2$. Initially, $s_1 = \sum_{j=0}^{n-1} grid[0][j]$, $s_2 = 0$. + +Then we enumerate the position $j$ where the first robot turns down. At this time, we update $s_1 = s_1 - grid[0][j]$. Then the sum of the optimal path of the second robot is $max(s_1, s_2)$. We take the minimum of $max(s_1, s_2)$ for all $j$. Then we update $s_2 = s_2 + grid[1][j]$. + +After the enumeration, we return the answer. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the number of columns in the grid. + ### **Python3** diff --git a/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README_EN.md b/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README_EN.md index 6dbad622435b6..5f3894a07b4c4 100644 --- a/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README_EN.md +++ b/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README_EN.md @@ -55,6 +55,27 @@ ## Solutions +**Solution 1: Enumeration** + +We can enumerate each position $(i, j)$ in the matrix, and judge whether we can place the word `word` from left to right or from right to left, or from top to bottom or from bottom to top, starting from this position. + +The following conditions must be met for this position to be used as a starting point: + +1. If the word `word` is to be placed from left to right, then this position must be the left boundary, or the cell `board[i][j - 1]` to the left of this position is `'#'`. +2. If the word `word` is to be placed from right to left, then this position must be the right boundary, or the cell `board[i][j + 1]` to the right of this position is `'#'`. +3. If the word `word` is to be placed from top to bottom, then this position must be the upper boundary, or the cell `board[i - 1][j]` above this position is `'#'`. +4. If the word `word` is to be placed from bottom to top, then this position must be the lower boundary, or the cell `board[i + 1][j]` below this position is `'#'`. + +Under the above conditions, we can start from this position and judge whether the word `word` can be placed. We design a function $check(i, j, a, b)$, which represents whether it is legal to place the word `word` from the position $(i, j)$ in the direction $(a, b)$. If it is legal, return `true`, otherwise return `false`. + +The implementation of the function $check(i, j, a, b)$ is as follows: + +We first get the other boundary position $(x, y)$ in the current direction, i.e., $(x, y) = (i + a \times k, j + b \times k)$, where $k$ is the length of the word `word`. If $(x, y)$ is in the matrix and the cell at $(x, y)$ is not `'#'`, it means that the other boundary position in the current direction is not `'#'`, so the word `word` cannot be placed, and `false` is returned. + +Otherwise, we start from the position $(i, j)$ and traverse the word `word` in the direction $(a, b)$. If we encounter a cell `board[i][j]` that is not a space or not the current character of the word `word`, it means that the word `word` cannot be placed, and `false` is returned. If the word `word` is traversed, it means that the word `word` can be placed, and `true` is returned. + +The time complexity is $O(m \times n)$, and the space complexity is $O(1)$. Here, $m$ and $n$ are the number of rows and columns in the matrix, respectively. + ### **Python3** diff --git a/solution/2000-2099/2019.The Score of Students Solving Math Expression/README_EN.md b/solution/2000-2099/2019.The Score of Students Solving Math Expression/README_EN.md index 39d27dd4a3c40..00f118e8c02d8 100644 --- a/solution/2000-2099/2019.The Score of Students Solving Math Expression/README_EN.md +++ b/solution/2000-2099/2019.The Score of Students Solving Math Expression/README_EN.md @@ -69,6 +69,31 @@ The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10. ## Solutions +**Solution 1: Dynamic Programming (Interval DP)** + +First, we design a function $cal(s)$ to calculate the result of a valid mathematical expression that only contains single-digit numbers. The correct answer is $x = cal(s)$. + +Let the length of the string $s$ be $n$, then the number of digits in $s$ is $m = \frac{n+1}{2}$. + +We define $f[i][j]$ as the possible values of the result calculated by selecting the digits from the $i$-th to the $j$-th in $s$ (index starts from $0$). Initially, $f[i][i]$ represents the selection of the $i$-th digit, and the result can only be this digit itself, i.e., $f[i][i] = \{s[i \times 2]\}$ (the $i$-th digit maps to the character at index $i \times 2$ in the string $s$). + +Next, we enumerate $i$ from large to small, and then enumerate $j$ from small to large. We need to find out the possible values of the results of the operation of all digits in the interval $[i, j]$. We enumerate the boundary point $k$ in the interval $[i, j]$, then $f[i][j]$ can be obtained from $f[i][k]$ and $f[k+1][j]$ through the operator $s[k \times 2 + 1]$. Therefore, we can get the following state transition equation: + +$$ +f[i][j] = \begin{cases} +\{s[i \times 2]\}, & i = j \\ +\bigcup\limits_{k=i}^{j-1} \{f[i][k] \otimes f[k+1][j]\}, & i < j +\end{cases} +$$ + +Where $\otimes$ represents the operator, i.e., $s[k \times 2 + 1]$. + +The possible values of the results of all digit operations in the string $s$ are $f[0][m-1]$. + +Finally, we count the answer. We use an array $cnt$ to count the number of times each answer appears in the answer array $answers$. If the answer is equal to $x$, then this student gets $5$ points, otherwise if the answer is in $f[0][m-1]$, then this student gets $2$ points. Traverse $cnt$ to count the answer. + +The time complexity is $O(n^3 \times M^2)$, and the space complexity is $O(n^2 \times M^2)$. Here, $M$ is the maximum possible value of the answer, and $n$ is the number of digits in the length of the string $s$. + ### **Python3** diff --git a/solution/2000-2099/2021.Brightest Position on Street/README_EN.md b/solution/2000-2099/2021.Brightest Position on Street/README_EN.md index b8a1b0d53282e..d9f8294388bc9 100644 --- a/solution/2000-2099/2021.Brightest Position on Street/README_EN.md +++ b/solution/2000-2099/2021.Brightest Position on Street/README_EN.md @@ -64,6 +64,16 @@ Out of all these positions, -1 is the smallest, so return it. ## Solutions +**Solution 1: Difference Array + Hash Table + Sorting** + +We can consider the range illuminated by each street light as an interval, with the left endpoint $l = position_i - range_i$ and the right endpoint $r = position_i + range_i$. We can use the idea of a difference array. For each interval $[l, r]$, we add $1$ to the value at position $l$ and subtract $1$ from the value at position $r + 1$. We use a hash table to maintain the change value at each position. + +Then we traverse each position in ascending order, calculate the brightness $s$ at the current position. If the previous maximum brightness $mx < s$, then update the maximum brightness $mx = s$ and record the current position $ans = i$. + +Finally, return $ans$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of `lights`. + ### **Python3** diff --git a/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README_EN.md b/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README_EN.md index 89b076424d40b..8a7099bf4ec23 100644 --- a/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README_EN.md +++ b/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README_EN.md @@ -50,6 +50,14 @@ It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D arra ## Solutions +**Solution 1: Simulation** + +According to the problem description, we know that to construct an $m$-row and $n$-column two-dimensional array, it needs to satisfy that $m \times n$ equals the length of the original array. If it does not satisfy, return an empty array directly. + +If it does satisfy, we can follow the process described in the problem, and put the elements from the original array into the two-dimensional array in order. + +The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows and columns of the two-dimensional array, respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README.md b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README.md index a3ffbf8270540..df0da51095ff8 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README.md +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README.md @@ -63,7 +63,7 @@ 遍历数组 `nums`,对于每个 $i$,枚举所有 $j$,如果 $i \neq j$ 且 $nums[i] + nums[j] = target$,则答案加一。 -时间复杂度 $O(n^2 \times m)$,空间复杂度 $O(1)$。其中 $n$ 和 $m$ 分别为数组 `nums` 和字符串 `target` 的长度。 +时间复杂度 $O(n^2 \times m)$,其中 $n$ 和 $m$ 分别为数组 `nums` 和字符串 `target` 的长度。空间复杂度 $O(1)$。 **方法二:哈希表** @@ -126,7 +126,7 @@ class Solution { public int numOfPairs(String[] nums, String target) { Map cnt = new HashMap<>(); for (String x : nums) { - cnt.put(x, cnt.getOrDefault(x, 0) + 1); + cnt.merge(x, 1, Integer::sum); } int ans = 0; for (int i = 1; i < target.length(); ++i) { diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README_EN.md b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README_EN.md index b019959c6bdc3..624be1a4f7a47 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README_EN.md +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README_EN.md @@ -56,6 +56,18 @@ ## Solutions +**Solution 1: Enumeration** + +Traverse the array `nums`, for each $i$, enumerate all $j$, if $i \neq j$ and $nums[i] + nums[j] = target$, then increment the answer by one. + +The time complexity is $O(n^2 \times m)$, where $n$ and $m$ are the lengths of the array `nums` and the string `target`, respectively. The space complexity is $O(1)$. + +**Solution 2: Hash Table** + +We can use a hash table to count the occurrence of each string in the array `nums`, then traverse all prefixes and suffixes of the string `target`. If both the prefix and suffix are in the hash table, then increment the answer by the product of their occurrences. + +The time complexity is $O(n + m^2)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the array `nums` and the string `target`, respectively. + ### **Python3** @@ -107,7 +119,7 @@ class Solution { public int numOfPairs(String[] nums, String target) { Map cnt = new HashMap<>(); for (String x : nums) { - cnt.put(x, cnt.getOrDefault(x, 0) + 1); + cnt.merge(x, 1, Integer::sum); } int ans = 0; for (int i = 1; i < target.length(); ++i) { diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.java b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.java index bb4d08eb5d702..5852c65731c85 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.java +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/Solution.java @@ -1,21 +1,21 @@ -class Solution { - public int numOfPairs(String[] nums, String target) { - Map cnt = new HashMap<>(); - for (String x : nums) { - cnt.put(x, cnt.getOrDefault(x, 0) + 1); - } - int ans = 0; - for (int i = 1; i < target.length(); ++i) { - String a = target.substring(0, i); - String b = target.substring(i); - int x = cnt.getOrDefault(a, 0); - int y = cnt.getOrDefault(b, 0); - if (!a.equals(b)) { - ans += x * y; - } else { - ans += x * (y - 1); - } - } - return ans; - } +class Solution { + public int numOfPairs(String[] nums, String target) { + Map cnt = new HashMap<>(); + for (String x : nums) { + cnt.merge(x, 1, Integer::sum); + } + int ans = 0; + for (int i = 1; i < target.length(); ++i) { + String a = target.substring(0, i); + String b = target.substring(i); + int x = cnt.getOrDefault(a, 0); + int y = cnt.getOrDefault(b, 0); + if (!a.equals(b)) { + ans += x * y; + } else { + ans += x * (y - 1); + } + } + return ans; + } } \ No newline at end of file diff --git a/solution/2000-2099/2024.Maximize the Confusion of an Exam/README.md b/solution/2000-2099/2024.Maximize the Confusion of an Exam/README.md index 3497d0a682786..4cc7bec63f90e 100644 --- a/solution/2000-2099/2024.Maximize the Confusion of an Exam/README.md +++ b/solution/2000-2099/2024.Maximize the Confusion of an Exam/README.md @@ -62,6 +62,8 @@ +**方法一:滑动窗口** + 思路同 [1004. 最大连续 1 的个数 III](/solution/1000-1099/1004.Max%20Consecutive%20Ones%20III/README.md) 维护一个单调变长的窗口。这种窗口经常出现在寻求“最大窗口”的问题中:因为要求的是“最大”,所以我们没有必要缩短窗口,于是代码就少了缩短窗口的部分;从另一个角度讲,本题里的 K 是资源数,一旦透支,窗口就不能再增长了。 diff --git a/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README_EN.md b/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README_EN.md index d64265cc57775..f45dd5b8737de 100644 --- a/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README_EN.md +++ b/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README_EN.md @@ -57,6 +57,18 @@ There are four ways to partition the array. ## Solutions +**Solution 1: Prefix Sum + Hash Table** + +We can preprocess to get the prefix sum array $s$ corresponding to the array $nums$, where $s[i]$ represents the sum of the array $nums[0,...i-1]$. Therefore, the sum of all elements in the array is $s[n - 1]$. + +If we do not modify the array $nums$, the condition for the sums of the two subarrays to be equal is that $s[n - 1]$ must be even. If $s[n - 1]$ is even, then we calculate $ans = \frac{right[s[n - 1] / 2]}{2}$. + +If we modify the array $nums$, we can enumerate each modification position $i$, change $nums[i]$ to $k$, then the change in the total sum of the array is $d = k - nums[i]$. At this time, the sum of the left part of $i$ remains unchanged, so the legal split must satisfy $s[i] = s[n - 1] + d - s[i]$, that is, $s[i] = \frac{s[n - 1] + d}{2}$. Each prefix sum of the right part has increased by $d$, so the legal split must satisfy $s[i] + d = s[n - 1] + d - (s[i] + d)$, that is, $s[i] = \frac{s[n - 1] - d}{2}$. We use hash tables $left$ and $right$ to record the number of times each prefix sum appears in the left and right parts, respectively. Then we can calculate $ans = max(ans, left[\frac{s[n - 1] + d}{2}]) + right[\frac{s[n - 1] - d}{2}]$. + +Finally, we return $ans$. + +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/2000-2099/2027.Minimum Moves to Convert String/README_EN.md b/solution/2000-2099/2027.Minimum Moves to Convert String/README_EN.md index 358c4eb8faa3c..77f218c7be286 100644 --- a/solution/2000-2099/2027.Minimum Moves to Convert String/README_EN.md +++ b/solution/2000-2099/2027.Minimum Moves to Convert String/README_EN.md @@ -47,6 +47,12 @@ Then we select the last 3 characters and convert them so that the final string c ## Solutions +**Solution 1: Greedy Algorithm** + +Traverse the string $s$. Whenever you encounter `'X'`, move the pointer $i$ three steps forward and add $1$ to the answer; otherwise, move the pointer $i$ one step forward. + +The time complexity is $O(n)$, where $n$ represents the length of the string $s$. + ### **Python3** diff --git a/solution/2000-2099/2028.Find Missing Observations/README_EN.md b/solution/2000-2099/2028.Find Missing Observations/README_EN.md index 85a332415c0f2..e4adf847cc447 100644 --- a/solution/2000-2099/2028.Find Missing Observations/README_EN.md +++ b/solution/2000-2099/2028.Find Missing Observations/README_EN.md @@ -50,6 +50,16 @@ ## Solutions +**Solution 1: Construction** + +According to the problem description, the sum of all numbers is $(n + m) \times mean$, and the sum of known numbers is `sum(rolls)`. Therefore, the sum of the missing numbers is $s = (n + m) \times mean - sum(rolls)$. + +If $s > n \times 6$ or $s < n$, it means there is no answer that satisfies the conditions, so return an empty array. + +Otherwise, we can evenly distribute $s$ to $n$ numbers, that is, the value of each number is $s / n$, and the value of $s \bmod n$ numbers is increased by $1$. + +The time complexity is $O(n + m)$, and the space complexity is $O(1)$. Here, $n$ and $m$ are the number of missing numbers and known numbers, respectively. + ### **Python3** diff --git a/solution/2000-2099/2032.Two Out of Three/README_EN.md b/solution/2000-2099/2032.Two Out of Three/README_EN.md index e1db346fe7782..07de98b48dbc7 100644 --- a/solution/2000-2099/2032.Two Out of Three/README_EN.md +++ b/solution/2000-2099/2032.Two Out of Three/README_EN.md @@ -46,6 +46,12 @@ Given three integer arrays nums1, nums2, and num ## Solutions +**Solution 1: Array + Enumeration** + +We can first put each element of the arrays into an array, then enumerate each number $i$ from $1$ to $100$, and check whether $i$ appears in at least two arrays. If so, add $i$ to the answer array. + +The time complexity is $O(n_1 + n_2 + n_3)$, and the space complexity is $O(n_1 + n_2 + n_3)$. Here, $n_1, n_2, n_3$ are the lengths of the arrays `nums1`, `nums2`, and `nums3`, respectively. + ### **Python3** diff --git a/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README_EN.md b/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README_EN.md index d2ca7bda7d498..5849d97181fcb 100644 --- a/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README_EN.md +++ b/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README_EN.md @@ -52,6 +52,14 @@ A total of 4 operations were used. ## Solutions +**Solution 1: Greedy** + +Firstly, to make the grid a single-value grid, the remainder of all elements of the grid with $x$ must be the same. + +Therefore, we can first traverse the grid to check whether the remainder of all elements with $x$ is the same. If not, return $-1$. Otherwise, we put all elements into an array, sort the array, take the median, then traverse the array, calculate the difference between each element and the median, divide it by $x$, and add all the differences to get the 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 of the grid, respectively. + ### **Python3** diff --git a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md index 5baedfbfacad6..3190e4ad6ea52 100644 --- a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md +++ b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md @@ -55,9 +55,9 @@ The alternating subarray sum is 1. **Solution 1: Dynamic Programming** -We define $f$ as the maximum alternating subarray sum ending with $nums[i]$, and $g$ as the maximum alternating subarray sum ending with $-nums[i]$. Initially, $f$ and $g$ are both $-\infty$. +We define $f$ as the maximum sum of the alternating subarray ending with $nums[i]$, and define $g$ as the maximum sum of the alternating subarray ending with $-nums[i]$. Initially, both $f$ and $g$ are $-\infty$. -Next, we traverse the array $nums$. For each position $i$, we need to maintain the values of $f$ and $g$, which are $f = \max(g, 0) + nums[i]$ and $g = f - nums[i]$, respectively. The answer is the maximum value among all $f$ and $g$. +Next, we traverse the array $nums$. For position $i$, we need to maintain the values of $f$ and $g$, i.e., $f = \max(g, 0) + nums[i]$, and $g = f - nums[i]$. The answer is the maximum value among all $f$ and $g$. The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. diff --git a/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README_EN.md b/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README_EN.md index 8d42cfac0d176..2646bbc35a64a 100644 --- a/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README_EN.md +++ b/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README_EN.md @@ -67,6 +67,12 @@ In total, 1 + 3 + 0 + 0 = 4 moves were used. ## Solutions +**Solution 1: Sorting** + +Sort both arrays, then traverse the two arrays, calculate the distance between each student's seat and their actual seat, and add all the distances to get 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 the arrays `seats` and `students`. + ### **Python3** diff --git a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README_EN.md b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README_EN.md index 3ecbe0b60a0ac..3b8f07e15d017 100644 --- a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README_EN.md +++ b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README_EN.md @@ -55,6 +55,14 @@ They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12. ## Solutions +**Solution 1: Simulation** + +We can split the string $s$ into several words by spaces. Then, for each word, check if it is a number. If it is a number, convert it to an integer, compare it with the previous number. If it is not strictly increasing, return `false`. Otherwise, assign the current number to the previous number and continue the traversal. + +If the traversal ends, it means that the numbers in the string are strictly increasing, so return `true`. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$. + ### **Python3** diff --git a/solution/2000-2099/2043.Simple Bank System/README_EN.md b/solution/2000-2099/2043.Simple Bank System/README_EN.md index cdcb8b526f6e7..ff6afeae2609a 100644 --- a/solution/2000-2099/2043.Simple Bank System/README_EN.md +++ b/solution/2000-2099/2043.Simple Bank System/README_EN.md @@ -57,6 +57,17 @@ bank.withdraw(10, 50); // return false, it is invalid because account 10 does ## Solutions +**Solution 1: Simulation** + +According to the problem description, we can use an array `balance` to simulate the balance of bank accounts. The array index starts from 0, and the value of the array represents the balance of the account. + +- During initialization, we assign the `balance` array to the member variable `this.balance`, and assign the length of `balance` to the member variable `this.n`. +- In the `transfer` function, if `account1` or `account2` is greater than `n` or `balance[account1 - 1]` is less than `money`, return `false`. Otherwise, subtract `money` from `balance[account1 - 1]`, add `money` to `balance[account2 - 1]`, and return `true`. +- In the `deposit` function, if `account` is greater than `n`, return `false`. Otherwise, add `money` to `balance[account - 1]`, and return `true`. +- In the `withdraw` function, if `account` is greater than `n` or `balance[account - 1]` is less than `money`, return `false`. Otherwise, subtract `money` from `balance[account - 1]`, and return `true`. + +The time complexity of the above operations is $O(1)$, and the space complexity is $O(n)$. Here, $n$ is the length of `balance`. + ### **Python3** diff --git a/solution/config.py b/solution/config.py index d294ac1d000b0..030d4d43fbf7f 100644 --- a/solution/config.py +++ b/solution/config.py @@ -39,6 +39,7 @@ 1994, 2004, 2010, + 2015, 2043, 2111, 2117,