From 1fbf9f443fd55762edc25ecaf4fba446272d3f81 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Fri, 24 Jan 2025 15:43:22 +0800 Subject: [PATCH] feat: add solutions to lc problems: No.1991,1985 --- .../README.md | 25 ----- .../README_EN.md | 30 ------ .../Solution.java | 23 +++-- .../Solution2.java | 25 ----- .../README.md | 19 ++-- .../README_EN.md | 19 ++-- .../Solution.cpp | 7 +- .../Solution.py | 8 +- .../README_EN.md | 12 ++- .../README_EN.md | 19 +++- .../README.md | 4 +- .../README_EN.md | 10 +- .../README.md | 85 ++++++++++------- .../README_EN.md | 94 +++++++++++++------ .../Solution.cpp | 10 +- .../Solution.go | 16 ++-- .../Solution.java | 10 +- .../Solution.js | 10 +- .../Solution.py | 8 +- .../Solution.rs | 16 ++++ .../Solution.ts | 10 +- 21 files changed, 241 insertions(+), 219 deletions(-) delete mode 100644 solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution2.java create mode 100644 solution/1900-1999/1991.Find the Middle Index in Array/Solution.rs diff --git a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README.md b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README.md index 4a3a003aeb309..7e76f4d6d4afd 100644 --- a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README.md +++ b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README.md @@ -146,31 +146,6 @@ class Solution { } ``` -#### Java - -```java -class Solution { - public int minimizeTheDifference(int[][] mat, int target) { - Set f = new HashSet<>(); - f.add(0); - for (var row : mat) { - Set g = new HashSet<>(); - for (int a : f) { - for (int b : row) { - g.add(a + b); - } - } - f = g; - } - int ans = 1 << 30; - for (int v : f) { - ans = Math.min(ans, Math.abs(v - target)); - } - return ans; - } -} -``` - #### C++ ```cpp diff --git a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README_EN.md b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README_EN.md index 355e68a7aeaa4..c9c253d0f25a4 100644 --- a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README_EN.md +++ b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README_EN.md @@ -110,36 +110,6 @@ class Solution: #### Java -```java -class Solution { - public int minimizeTheDifference(int[][] mat, int target) { - boolean[] f = {true}; - for (var row : mat) { - int mx = 0; - for (int x : row) { - mx = Math.max(mx, x); - } - boolean[] g = new boolean[f.length + mx]; - for (int x : row) { - for (int j = x; j < f.length + x; ++j) { - g[j] |= f[j - x]; - } - } - f = g; - } - int ans = 1 << 30; - for (int j = 0; j < f.length; ++j) { - if (f[j]) { - ans = Math.min(ans, Math.abs(j - target)); - } - } - return ans; - } -} -``` - -#### Java - ```java class Solution { public int minimizeTheDifference(int[][] mat, int target) { diff --git a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.java b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.java index 29a820158575d..060a0a50ed85c 100644 --- a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.java +++ b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.java @@ -1,20 +1,25 @@ class Solution { public int minimizeTheDifference(int[][] mat, int target) { - Set f = new HashSet<>(); - f.add(0); + boolean[] f = {true}; for (var row : mat) { - Set g = new HashSet<>(); - for (int a : f) { - for (int b : row) { - g.add(a + b); + int mx = 0; + for (int x : row) { + mx = Math.max(mx, x); + } + boolean[] g = new boolean[f.length + mx]; + for (int x : row) { + for (int j = x; j < f.length + x; ++j) { + g[j] |= f[j - x]; } } f = g; } int ans = 1 << 30; - for (int v : f) { - ans = Math.min(ans, Math.abs(v - target)); + for (int j = 0; j < f.length; ++j) { + if (f[j]) { + ans = Math.min(ans, Math.abs(j - target)); + } } return ans; } -} \ No newline at end of file +} diff --git a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution2.java b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution2.java deleted file mode 100644 index fc8fbf863de36..0000000000000 --- a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution2.java +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { - public int minimizeTheDifference(int[][] mat, int target) { - boolean[] f = {true}; - for (var row : mat) { - int mx = 0; - for (int x : row) { - mx = Math.max(mx, x); - } - boolean[] g = new boolean[f.length + mx]; - for (int x : row) { - for (int j = x; j < f.length + x; ++j) { - g[j] |= f[j - x]; - } - } - f = g; - } - int ans = 1 << 30; - for (int j = 0; j < f.length; ++j) { - if (f[j]) { - ans = Math.min(ans, Math.abs(j - target)); - } - } - return ans; - } -} \ No newline at end of file diff --git a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README.md b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README.md index d3fef7d9de1f9..09cb0320691fc 100644 --- a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README.md +++ b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README.md @@ -78,7 +78,11 @@ nums 中的数字按非递减顺序排列为 ["0","0"] -### 方法一:自定义排序 +### 方法一:排序或快速选择 + +我们可以将 $\textit{nums}$ 数组中的字符串按照整数从大到小排序,然后取第 $k$ 个元素即可。也可以使用快速选择算法,找到第 $k$ 大的整数。 + +时间复杂度 $O(n \times \log n)$ 或 $O(n)$,其中 $n$ 是 $\textit{nums}$ 数组的长度。空间复杂度 $O(\log n)$ 或 $O(1)$。 @@ -87,13 +91,7 @@ nums 中的数字按非递减顺序排列为 ["0","0"] ```python class Solution: def kthLargestNumber(self, nums: List[str], k: int) -> str: - def cmp(a, b): - if len(a) != len(b): - return len(b) - len(a) - return 1 if b > a else -1 - - nums.sort(key=cmp_to_key(cmp)) - return nums[k - 1] + return nlargest(k, nums, key=lambda x: int(x))[k - 1] ``` #### Java @@ -114,8 +112,9 @@ class Solution { class Solution { public: string kthLargestNumber(vector& nums, int k) { - auto cmp = [](const string& a, const string& b) { return a.size() == b.size() ? a > b : a.size() > b.size(); }; - sort(nums.begin(), nums.end(), cmp); + nth_element(nums.begin(), nums.begin() + k - 1, nums.end(), [](const string& a, const string& b) { + return a.size() == b.size() ? a > b : a.size() > b.size(); + }); return nums[k - 1]; } }; diff --git a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README_EN.md b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README_EN.md index ba1b62fb1f919..ddc05cf0ba032 100644 --- a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README_EN.md +++ b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README_EN.md @@ -76,7 +76,11 @@ The 2nd largest integer in nums is "0". -### Solution 1 +### Solution 1: Sorting or Quickselect + +We can sort the strings in the $\textit{nums}$ array in descending order as integers, and then take the $k$-th element. Alternatively, we can use the quickselect algorithm to find the $k$-th largest integer. + +The time complexity is $O(n \times \log n)$ or $O(n)$, where $n$ is the length of the $\textit{nums}$ array. The space complexity is $O(\log n)$ or $O(1)$. @@ -85,13 +89,7 @@ The 2nd largest integer in nums is "0". ```python class Solution: def kthLargestNumber(self, nums: List[str], k: int) -> str: - def cmp(a, b): - if len(a) != len(b): - return len(b) - len(a) - return 1 if b > a else -1 - - nums.sort(key=cmp_to_key(cmp)) - return nums[k - 1] + return nlargest(k, nums, key=lambda x: int(x))[k - 1] ``` #### Java @@ -112,8 +110,9 @@ class Solution { class Solution { public: string kthLargestNumber(vector& nums, int k) { - auto cmp = [](const string& a, const string& b) { return a.size() == b.size() ? a > b : a.size() > b.size(); }; - sort(nums.begin(), nums.end(), cmp); + nth_element(nums.begin(), nums.begin() + k - 1, nums.end(), [](const string& a, const string& b) { + return a.size() == b.size() ? a > b : a.size() > b.size(); + }); return nums[k - 1]; } }; diff --git a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.cpp b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.cpp index 5c7e4d79cdbd0..29e64418be335 100644 --- a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.cpp +++ b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.cpp @@ -1,8 +1,9 @@ class Solution { public: string kthLargestNumber(vector& nums, int k) { - auto cmp = [](const string& a, const string& b) { return a.size() == b.size() ? a > b : a.size() > b.size(); }; - sort(nums.begin(), nums.end(), cmp); + nth_element(nums.begin(), nums.begin() + k - 1, nums.end(), [](const string& a, const string& b) { + return a.size() == b.size() ? a > b : a.size() > b.size(); + }); return nums[k - 1]; } -}; \ No newline at end of file +}; diff --git a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.py b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.py index 59dd847afef25..d349e386040a9 100644 --- a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.py +++ b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.py @@ -1,9 +1,3 @@ class Solution: def kthLargestNumber(self, nums: List[str], k: int) -> str: - def cmp(a, b): - if len(a) != len(b): - return len(b) - len(a) - return 1 if b > a else -1 - - nums.sort(key=cmp_to_key(cmp)) - return nums[k - 1] + return nlargest(k, nums, key=lambda x: int(x))[k - 1] diff --git a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README_EN.md b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README_EN.md index 18c712efc0a19..c8390fb5691bb 100644 --- a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README_EN.md +++ b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README_EN.md @@ -81,7 +81,17 @@ tags: -### Solution 1 +### Solution 1: State Compression Dynamic Programming + Subset Enumeration + +We note that $n$ does not exceed $14$, so we can consider using state compression dynamic programming to solve this problem. + +We use a binary number $i$ of length $n$ to represent the current task state, where the $j$-th bit of $i$ is $1$ if and only if the $j$-th task is completed. We use $f[i]$ to represent the minimum number of work sessions needed to complete all tasks with state $i$. + +We can enumerate all subsets $j$ of $i$, where each bit of the binary representation of $j$ is a subset of the corresponding bit of the binary representation of $i$, i.e., $j \subseteq i$. If the tasks corresponding to $j$ can be completed in one work session, then we can update $f[i]$ using $f[i \oplus j] + 1$, where $i \oplus j$ represents the bitwise XOR of $i$ and $j$. + +The final answer is $f[2^n - 1]$. + +The time complexity is $O(n \times 3^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the number of tasks. diff --git a/solution/1900-1999/1987.Number of Unique Good Subsequences/README_EN.md b/solution/1900-1999/1987.Number of Unique Good Subsequences/README_EN.md index 4a1643e6b8baf..d833d26e858ab 100644 --- a/solution/1900-1999/1987.Number of Unique Good Subsequences/README_EN.md +++ b/solution/1900-1999/1987.Number of Unique Good Subsequences/README_EN.md @@ -54,7 +54,7 @@ The unique good subsequences are "1" and "11".
 Input: binary = "101"
 Output: 5
-Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"]. 
+Explanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"].
 The unique good subsequences are "0", "1", "10", "11", and "101".
 
@@ -72,7 +72,22 @@ The unique good subsequences are "0", "1", "10", & -### Solution 1 +### Solution 1: Dynamic Programming + +We define $f$ as the number of distinct good subsequences ending with $1$, and $g$ as the number of distinct good subsequences ending with $0$ and starting with $1$. Initially, $f = g = 0$. + +For a binary string, we can traverse each bit from left to right. Suppose the current bit is $c$: + +- If $c = 0$, we can append $c$ to the $f$ and $g$ distinct good subsequences, so update $g = (g + f) \bmod (10^9 + 7)$; +- If $c = 1$, we can append $c$ to the $f$ and $g$ distinct good subsequences, and also append $c$ alone, so update $f = (f + g + 1) \bmod (10^9 + 7)$. + +If the string contains $0$, the final answer is $f + g + 1$, otherwise the answer is $f + g$. + +The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$. + +Similar problems: + +- [940. Distinct Subsequences II](https://github.com/doocs/leetcode/blob/main/solution/0900-0999/0940.Distinct%20Subsequences%20II/README_EN.md) diff --git a/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README.md b/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README.md index de9d457858eb2..bfa230c9c32d2 100644 --- a/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README.md +++ b/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README.md @@ -75,11 +75,11 @@ tags: 我们可以用两个指针 $i$ 和 $j$ 指向鬼和非鬼的人,初始时 $i=0$, $j=0$。 -然后我们从左到右遍历数组,当遇到鬼时,即 $team[i]=1$ 时,如果此时 $j \lt n$ 并且 $team[j]=1$ 或者 $i - j \gt dist$,则指针 $j$ 循环右移,也即是说,我们要找到第一个不是鬼的人,且 $i$ 和 $j$ 之间的距离不超过 $dist$。如果找到了这样的人,则将指针 $j$ 右移一位,表示我们已经抓住了这个人,同时答案加一。继续遍历数组,直到遍历完整个数组。 +然后我们从左到右遍历数组,当遇到鬼时,即 $team[i]=1$ 时,如果此时 $j \lt n$ 并且 $\textit{team}[j]=1$ 或者 $i - j \gt \textit{dist}$,则指针 $j$ 循环右移,也即是说,我们要找到第一个不是鬼的人,且 $i$ 和 $j$ 之间的距离不超过 $\textit{dist}$。如果找到了这样的人,则将指针 $j$ 右移一位,表示我们已经抓住了这个人,同时答案加一。继续遍历数组,直到遍历完整个数组。 最后返回答案即可。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。 +时间复杂度 $O(n)$,其中 $n$ 为数组 $\textit{team}$ 的长度。空间复杂度 $O(1)$。 diff --git a/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README_EN.md b/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README_EN.md index 946ab86ecb64d..ee9559c3e45b9 100644 --- a/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README_EN.md +++ b/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README_EN.md @@ -69,7 +69,15 @@ There are no people who are not "it" to catch. -### Solution 1 +### Solution 1: Two Pointers + +We can use two pointers $i$ and $j$ to point to the ghost and non-ghost people, initially $i=0$, $j=0$. + +Then we traverse the array from left to right. When we encounter a ghost, i.e., $team[i]=1$, if $j \lt n$ and $\textit{team}[j]=1$ or $i - j \gt \textit{dist}$, then move pointer $j$ to the right in a loop. This means we need to find the first non-ghost person such that the distance between $i$ and $j$ does not exceed $\textit{dist}$. If such a person is found, move pointer $j$ one step to the right, indicating that we have caught this person, and increment the answer by one. Continue traversing the array until the entire array is processed. + +Finally, return the answer. + +The time complexity is $O(n)$, where $n$ is the length of the array $\textit{team}$. The space complexity is $O(1)$. diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/README.md b/solution/1900-1999/1991.Find the Middle Index in Array/README.md index 8da4d8155eb14..284cfac36ea47 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/README.md +++ b/solution/1900-1999/1991.Find the Middle Index in Array/README.md @@ -89,13 +89,13 @@ tags: ### 方法一:前缀和 -我们定义变量 $left$ 表示数组 `nums` 中下标 $i$ 左侧元素之和,变量 $right$ 表示数组 `nums` 中下标 $i$ 右侧元素之和。初始时 $left = 0$, $right = \sum_{i = 0}^{n - 1} nums[i]$。 +我们定义两个变量 $l$ 和 $r$,分别表示数组 $\textit{nums}$ 中下标 $i$ 左侧元素之和和右侧元素之和。初始时 $l = 0$,而 $r = \sum_{i = 0}^{n - 1} nums[i]$。 -遍历数组 `nums`,对于当前遍历到的数字 $x$,我们更新 $right = right - x$,此时如果 $left=right$,说明当前下标 $i$ 就是中间位置,直接返回即可。否则,我们更新 $left = left + x$,继续遍历下一个数字。 +我们遍历数组 $\textit{nums}$,对于当前遍历到的数字 $x$,我们更新 $r = r - x$,此时如果 $l = r$,说明当前下标 $i$ 就是中间位置,直接返回即可。否则,我们更新 $l = l + x$,继续遍历下一个数字。 遍历结束,如果没有找到中间位置,返回 $-1$。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n)$,其中 $n$ 为数组 $\textit{nums}$ 的长度。空间复杂度 $O(1)$。 相似题目: @@ -109,12 +109,12 @@ tags: ```python class Solution: def findMiddleIndex(self, nums: List[int]) -> int: - left, right = 0, sum(nums) + l, r = 0, sum(nums) for i, x in enumerate(nums): - right -= x - if left == right: + r -= x + if l == r: return i - left += x + l += x return -1 ``` @@ -123,13 +123,13 @@ class Solution: ```java class Solution { public int findMiddleIndex(int[] nums) { - int left = 0, right = Arrays.stream(nums).sum(); + int l = 0, r = Arrays.stream(nums).sum(); for (int i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l == r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; } @@ -142,13 +142,13 @@ class Solution { class Solution { public: int findMiddleIndex(vector& nums) { - int left = 0, right = accumulate(nums.begin(), nums.end(), 0); + int l = 0, r = accumulate(nums.begin(), nums.end(), 0); for (int i = 0; i < nums.size(); ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l == r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; } @@ -159,16 +159,16 @@ public: ```go func findMiddleIndex(nums []int) int { - s := 0 - for _, num := range nums { - s += num + l, r := 0, 0 + for _, x := range nums { + r += x } - total := 0 - for i, num := range nums { - total += num - if total-num == s-total { + for i, x := range nums { + r -= x + if l == r { return i } + l += x } return -1 } @@ -178,19 +178,40 @@ func findMiddleIndex(nums []int) int { ```ts function findMiddleIndex(nums: number[]): number { - let left = 0, - right = nums.reduce((a, b) => a + b); + let l = 0; + let r = nums.reduce((a, b) => a + b, 0); for (let i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l === r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; } ``` +#### Rust + +```rust +impl Solution { + pub fn find_middle_index(nums: Vec) -> i32 { + let mut l = 0; + let mut r: i32 = nums.iter().sum(); + + for (i, &x) in nums.iter().enumerate() { + r -= x; + if l == r { + return i as i32; + } + l += x; + } + + -1 + } +} +``` + #### JavaScript ```js @@ -199,14 +220,14 @@ function findMiddleIndex(nums: number[]): number { * @return {number} */ var findMiddleIndex = function (nums) { - let left = 0, - right = nums.reduce((a, b) => a + b); + let l = 0; + let r = nums.reduce((a, b) => a + b, 0); for (let i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l === r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; }; diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/README_EN.md b/solution/1900-1999/1991.Find the Middle Index in Array/README_EN.md index 566edbe82ff6c..36277d5020b73 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/README_EN.md +++ b/solution/1900-1999/1991.Find the Middle Index in Array/README_EN.md @@ -71,7 +71,20 @@ The sum of the numbers after index 2 is: 0 -### Solution 1 +### Solution 1: Prefix Sum + +We define two variables $l$ and $r$, representing the sum of elements to the left and right of index $i$ in the array $\textit{nums}$, respectively. Initially, $l = 0$ and $r = \sum_{i = 0}^{n - 1} \textit{nums}[i]$. + +We traverse the array $\textit{nums}$, and for the current number $x$, we update $r = r - x$. If $l = r$ at this point, it means the current index $i$ is the middle index, and we return it directly. Otherwise, we update $l = l + x$ and continue to the next number. + +If the traversal ends without finding a middle index, return $-1$. + +The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$. + +Similar problems: + +- [0724. Find Pivot Index](https://github.com/doocs/leetcode/blob/main/solution/0700-0799/0724.Find%20Pivot%20Index/README_EN.md) +- [2574. Left and Right Sum Differences](https://github.com/doocs/leetcode/blob/main/solution/2500-2599/2574.Left%20and%20Right%20Sum%20Differences/README_EN.md) @@ -80,12 +93,12 @@ The sum of the numbers after index 2 is: 0 ```python class Solution: def findMiddleIndex(self, nums: List[int]) -> int: - left, right = 0, sum(nums) + l, r = 0, sum(nums) for i, x in enumerate(nums): - right -= x - if left == right: + r -= x + if l == r: return i - left += x + l += x return -1 ``` @@ -94,13 +107,13 @@ class Solution: ```java class Solution { public int findMiddleIndex(int[] nums) { - int left = 0, right = Arrays.stream(nums).sum(); + int l = 0, r = Arrays.stream(nums).sum(); for (int i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l == r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; } @@ -113,13 +126,13 @@ class Solution { class Solution { public: int findMiddleIndex(vector& nums) { - int left = 0, right = accumulate(nums.begin(), nums.end(), 0); + int l = 0, r = accumulate(nums.begin(), nums.end(), 0); for (int i = 0; i < nums.size(); ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l == r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; } @@ -130,16 +143,16 @@ public: ```go func findMiddleIndex(nums []int) int { - s := 0 - for _, num := range nums { - s += num + l, r := 0, 0 + for _, x := range nums { + r += x } - total := 0 - for i, num := range nums { - total += num - if total-num == s-total { + for i, x := range nums { + r -= x + if l == r { return i } + l += x } return -1 } @@ -149,19 +162,40 @@ func findMiddleIndex(nums []int) int { ```ts function findMiddleIndex(nums: number[]): number { - let left = 0, - right = nums.reduce((a, b) => a + b); + let l = 0; + let r = nums.reduce((a, b) => a + b, 0); for (let i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l === r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; } ``` +#### Rust + +```rust +impl Solution { + pub fn find_middle_index(nums: Vec) -> i32 { + let mut l = 0; + let mut r: i32 = nums.iter().sum(); + + for (i, &x) in nums.iter().enumerate() { + r -= x; + if l == r { + return i as i32; + } + l += x; + } + + -1 + } +} +``` + #### JavaScript ```js @@ -170,14 +204,14 @@ function findMiddleIndex(nums: number[]): number { * @return {number} */ var findMiddleIndex = function (nums) { - let left = 0, - right = nums.reduce((a, b) => a + b); + let l = 0; + let r = nums.reduce((a, b) => a + b, 0); for (let i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l === r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; }; diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.cpp b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.cpp index 8c5da028e2197..0d361fb08b9a9 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.cpp +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.cpp @@ -1,14 +1,14 @@ class Solution { public: int findMiddleIndex(vector& nums) { - int left = 0, right = accumulate(nums.begin(), nums.end(), 0); + int l = 0, r = accumulate(nums.begin(), nums.end(), 0); for (int i = 0; i < nums.size(); ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l == r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; } -}; \ No newline at end of file +}; diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.go b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.go index 58068c62e652f..b2971e48cfdce 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.go +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.go @@ -1,14 +1,14 @@ func findMiddleIndex(nums []int) int { - s := 0 - for _, num := range nums { - s += num + l, r := 0, 0 + for _, x := range nums { + r += x } - total := 0 - for i, num := range nums { - total += num - if total-num == s-total { + for i, x := range nums { + r -= x + if l == r { return i } + l += x } return -1 -} \ No newline at end of file +} diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.java b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.java index 6d1deffa3223b..4f8f64280642b 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.java +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.java @@ -1,13 +1,13 @@ class Solution { public int findMiddleIndex(int[] nums) { - int left = 0, right = Arrays.stream(nums).sum(); + int l = 0, r = Arrays.stream(nums).sum(); for (int i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l == r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; } -} \ No newline at end of file +} diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.js b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.js index 044cc0459f7ba..cc5256e9343d5 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.js +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.js @@ -3,14 +3,14 @@ * @return {number} */ var findMiddleIndex = function (nums) { - let left = 0, - right = nums.reduce((a, b) => a + b); + let l = 0; + let r = nums.reduce((a, b) => a + b, 0); for (let i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l === r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; }; diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.py b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.py index ffe7966f818f1..33f7c597d8d02 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.py +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.py @@ -1,9 +1,9 @@ class Solution: def findMiddleIndex(self, nums: List[int]) -> int: - left, right = 0, sum(nums) + l, r = 0, sum(nums) for i, x in enumerate(nums): - right -= x - if left == right: + r -= x + if l == r: return i - left += x + l += x return -1 diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.rs b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.rs new file mode 100644 index 0000000000000..4255f88f78e0d --- /dev/null +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn find_middle_index(nums: Vec) -> i32 { + let mut l = 0; + let mut r: i32 = nums.iter().sum(); + + for (i, &x) in nums.iter().enumerate() { + r -= x; + if l == r { + return i as i32; + } + l += x; + } + + -1 + } +} diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.ts b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.ts index 8d1bfe438c2dd..874e46706a72f 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/Solution.ts +++ b/solution/1900-1999/1991.Find the Middle Index in Array/Solution.ts @@ -1,12 +1,12 @@ function findMiddleIndex(nums: number[]): number { - let left = 0, - right = nums.reduce((a, b) => a + b); + let l = 0; + let r = nums.reduce((a, b) => a + b, 0); for (let i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { + r -= nums[i]; + if (l === r) { return i; } - left += nums[i]; + l += nums[i]; } return -1; }