From 6b4d81c7529cdeba1d4320dbacb4ee9ebb1982c8 Mon Sep 17 00:00:00 2001 From: Libin YANG Date: Thu, 16 Jan 2025 08:15:39 +0800 Subject: [PATCH 1/2] feat: add solutions to lc problems: No.713,3095,3097 (#3955) --- .../0705.Design HashSet/README_EN.md | 12 +- .../README.md | 171 ++++++++++-------- .../README_EN.md | 164 ++++++++++------- .../Solution.cpp | 15 +- .../Solution.cs | 14 ++ .../Solution.go | 23 +-- .../Solution.java | 15 +- .../Solution.js | 13 +- .../Solution.kt | 21 ++- .../Solution.py | 15 +- .../Solution.rs | 26 ++- .../Solution.ts | 13 +- .../README.md | 38 ++++ .../README_EN.md | 38 ++++ .../Solution.rs | 37 ++++ .../README.md | 38 ++++ .../README_EN.md | 38 ++++ .../Solution.rs | 37 ++++ 18 files changed, 516 insertions(+), 212 deletions(-) create mode 100644 solution/0700-0799/0713.Subarray Product Less Than K/Solution.cs create mode 100644 solution/3000-3099/3095.Shortest Subarray With OR at Least K I/Solution.rs create mode 100644 solution/3000-3099/3097.Shortest Subarray With OR at Least K II/Solution.rs diff --git a/solution/0700-0799/0705.Design HashSet/README_EN.md b/solution/0700-0799/0705.Design HashSet/README_EN.md index 93643c0395fdd..604bdd5eff431 100644 --- a/solution/0700-0799/0705.Design HashSet/README_EN.md +++ b/solution/0700-0799/0705.Design HashSet/README_EN.md @@ -65,7 +65,13 @@ myHashSet.contains(2); // return False, (already removed) -### Solution 1 +### Solution 1: Static Array Implementation + +Directly create an array of size $1000001$, initially with each element set to `false`, indicating that the element does not exist in the hash set. + +When adding an element to the hash set, set the corresponding position in the array to `true`; when deleting an element, set the corresponding position in the array to `false`; when checking if an element exists, directly return the value at the corresponding position in the array. + +The time complexity of the above operations is $O(1)$. @@ -227,7 +233,9 @@ class MyHashSet { -### Solution 2 +### Solution 2: Array of Linked Lists + +We can also create an array of size $SIZE=1000$, where each position in the array is a linked list. diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/README.md b/solution/0700-0799/0713.Subarray Product Less Than K/README.md index 1e2980c19f8f0..ae84007727b0e 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/README.md +++ b/solution/0700-0799/0713.Subarray Product Less Than K/README.md @@ -58,22 +58,11 @@ tags: 我们可以用双指针维护一个滑动窗口,窗口内所有元素的乘积小于 $k$。 -初始时,左右指针都指向下标 0,然后不断地右移右指针,将元素加入窗口,此时判断窗口内所有元素的乘积是否大于等于 $k$,如果大于等于 $k$,则不断地左移左指针,将元素移出窗口,直到窗口内所有元素的乘积小于 $k$。然后我们记录此时的窗口大小,即为以右指针为右端点的满足条件的子数组个数,将其加入答案。 +定义两个指针 $l$ 和 $r$ 分别指向滑动窗口的左右边界,初始时 $l = r = 0$。我们用一个变量 $p$ 记录窗口内所有元素的乘积,初始时 $p = 1$。 -当右指针移动到数组末尾时,即可得到答案。 +每次,我们将 $r$ 右移一位,将 $r$ 指向的元素 $x$ 加入窗口,更新 $p = p \times x$。然后,如果 $p \geq k$,我们循环地将 $l$ 右移一位,并更新 $p = p \div \text{nums}[l]$,直到 $p < k$ 或者 $l \gt r$ 为止。这样,以 $r$ 结尾的、乘积小于 $k$ 的连续子数组的个数即为 $r - l + 1$。然后我们将答案加上这个数量,并继续移动 $r$,直到 $r$ 到达数组的末尾。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。 - -以下是双指针的常用算法模板: - -```java -for (int i = 0, j = 0; i < n; ++i) { - while (j < i && check(j, i)) { - ++j; - } - // 具体问题的逻辑 -} -``` +时间复杂度 $O(n)$,其中 $n$ 为数组的长度。空间复杂度 $O(1)$。 @@ -82,13 +71,14 @@ for (int i = 0, j = 0; i < n; ++i) { ```python class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: - ans, s, j = 0, 1, 0 - for i, v in enumerate(nums): - s *= v - while j <= i and s >= k: - s //= nums[j] - j += 1 - ans += i - j + 1 + ans = l = 0 + p = 1 + for r, x in enumerate(nums): + p *= x + while l <= r and p >= k: + p //= nums[l] + l += 1 + ans += r - l + 1 return ans ``` @@ -97,13 +87,14 @@ class Solution: ```java class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { - int ans = 0; - for (int i = 0, j = 0, s = 1; i < nums.length; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s /= nums[j++]; + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.length; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; } @@ -116,11 +107,14 @@ class Solution { class Solution { public: int numSubarrayProductLessThanK(vector& nums, int k) { - int ans = 0; - for (int i = 0, j = 0, s = 1; i < nums.size(); ++i) { - s *= nums[i]; - while (j <= i && s >= k) s /= nums[j++]; - ans += i - j + 1; + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.size(); ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; + } + ans += r - l + 1; } return ans; } @@ -130,16 +124,17 @@ public: #### Go ```go -func numSubarrayProductLessThanK(nums []int, k int) int { - ans := 0 - for i, j, s := 0, 0, 1; i < len(nums); i++ { - s *= nums[i] - for ; j <= i && s >= k; j++ { - s /= nums[j] - } - ans += i - j + 1 - } - return ans +func numSubarrayProductLessThanK(nums []int, k int) (ans int) { + l, p := 0, 1 + for r, x := range nums { + p *= x + for l <= r && p >= k { + p /= nums[l] + l++ + } + ans += r - l + 1 + } + return } ``` @@ -147,13 +142,14 @@ func numSubarrayProductLessThanK(nums []int, k int) int { ```ts function numSubarrayProductLessThanK(nums: number[], k: number): number { - let ans = 0; - for (let i = 0, j = 0, s = 1; i < nums.length; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s /= nums[j++]; + const n = nums.length; + let [ans, l, p] = [0, 0, 1]; + for (let r = 0; r < n; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; } @@ -164,22 +160,20 @@ function numSubarrayProductLessThanK(nums: number[], k: number): number { ```rust impl Solution { pub fn num_subarray_product_less_than_k(nums: Vec, k: i32) -> i32 { - if k <= 1 { - return 0; + let mut ans = 0; + let mut l = 0; + let mut p = 1; + + for (r, &x) in nums.iter().enumerate() { + p *= x; + while l <= r && p >= k { + p /= nums[l]; + l += 1; + } + ans += (r - l + 1) as i32; } - let mut res = 0; - let mut product = 1; - let mut i = 0; - nums.iter().enumerate().for_each(|(j, v)| { - product *= v; - while product >= k { - product /= nums[i]; - i += 1; - } - res += j - i + 1; - }); - res as i32 + ans } } ``` @@ -194,14 +188,13 @@ impl Solution { */ var numSubarrayProductLessThanK = function (nums, k) { const n = nums.length; - let ans = 0; - let s = 1; - for (let i = 0, j = 0; i < n; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s = Math.floor(s / nums[j++]); + let [ans, l, p] = [0, 0, 1]; + for (let r = 0; r < n; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; }; @@ -212,17 +205,39 @@ var numSubarrayProductLessThanK = function (nums, k) { ```kotlin class Solution { fun numSubarrayProductLessThanK(nums: IntArray, k: Int): Int { - var left = 0 - var count = 0 - var product = 1 - nums.forEachIndexed { right, num -> - product *= num - while (product >= k && left <= right) { - product /= nums[left++] + var ans = 0 + var l = 0 + var p = 1 + + for (r in nums.indices) { + p *= nums[r] + while (l <= r && p >= k) { + p /= nums[l] + l++ + } + ans += r - l + 1 + } + + return ans + } +} +``` + +#### C# + +```cs +public class Solution { + public int NumSubarrayProductLessThanK(int[] nums, int k) { + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.Length; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - count += right - left + 1 + ans += r - l + 1; } - return count + return ans; } } ``` diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/README_EN.md b/solution/0700-0799/0713.Subarray Product Less Than K/README_EN.md index 87340454962b7..2871fddc8c4a4 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/README_EN.md +++ b/solution/0700-0799/0713.Subarray Product Less Than K/README_EN.md @@ -54,7 +54,15 @@ Note that [10, 5, 2] is not included as the product of 100 is not strictly less -### Solution 1 +### Solution 1: Two Pointers + +We can use two pointers to maintain a sliding window, where the product of all elements in the window is less than $k$. + +Define two pointers $l$ and $r$ pointing to the left and right boundaries of the sliding window, initially $l = r = 0$. We use a variable $p$ to record the product of all elements in the window, initially $p = 1$. + +Each time, we move $r$ one step to the right, adding the element $x$ pointed to by $r$ to the window, and update $p = p \times x$. Then, if $p \geq k$, we move $l$ one step to the right in a loop and update $p = p \div \text{nums}[l]$ until $p < k$ or $l \gt r$. Thus, the number of contiguous subarrays ending at $r$ with a product less than $k$ is $r - l + 1$. We then add this number to the answer and continue moving $r$ until $r$ reaches the end of the array. + +The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. @@ -63,13 +71,14 @@ Note that [10, 5, 2] is not included as the product of 100 is not strictly less ```python class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: - ans, s, j = 0, 1, 0 - for i, v in enumerate(nums): - s *= v - while j <= i and s >= k: - s //= nums[j] - j += 1 - ans += i - j + 1 + ans = l = 0 + p = 1 + for r, x in enumerate(nums): + p *= x + while l <= r and p >= k: + p //= nums[l] + l += 1 + ans += r - l + 1 return ans ``` @@ -78,13 +87,14 @@ class Solution: ```java class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { - int ans = 0; - for (int i = 0, j = 0, s = 1; i < nums.length; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s /= nums[j++]; + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.length; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; } @@ -97,11 +107,14 @@ class Solution { class Solution { public: int numSubarrayProductLessThanK(vector& nums, int k) { - int ans = 0; - for (int i = 0, j = 0, s = 1; i < nums.size(); ++i) { - s *= nums[i]; - while (j <= i && s >= k) s /= nums[j++]; - ans += i - j + 1; + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.size(); ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; + } + ans += r - l + 1; } return ans; } @@ -111,16 +124,17 @@ public: #### Go ```go -func numSubarrayProductLessThanK(nums []int, k int) int { - ans := 0 - for i, j, s := 0, 0, 1; i < len(nums); i++ { - s *= nums[i] - for ; j <= i && s >= k; j++ { - s /= nums[j] - } - ans += i - j + 1 - } - return ans +func numSubarrayProductLessThanK(nums []int, k int) (ans int) { + l, p := 0, 1 + for r, x := range nums { + p *= x + for l <= r && p >= k { + p /= nums[l] + l++ + } + ans += r - l + 1 + } + return } ``` @@ -128,13 +142,14 @@ func numSubarrayProductLessThanK(nums []int, k int) int { ```ts function numSubarrayProductLessThanK(nums: number[], k: number): number { - let ans = 0; - for (let i = 0, j = 0, s = 1; i < nums.length; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s /= nums[j++]; + const n = nums.length; + let [ans, l, p] = [0, 0, 1]; + for (let r = 0; r < n; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; } @@ -145,22 +160,20 @@ function numSubarrayProductLessThanK(nums: number[], k: number): number { ```rust impl Solution { pub fn num_subarray_product_less_than_k(nums: Vec, k: i32) -> i32 { - if k <= 1 { - return 0; + let mut ans = 0; + let mut l = 0; + let mut p = 1; + + for (r, &x) in nums.iter().enumerate() { + p *= x; + while l <= r && p >= k { + p /= nums[l]; + l += 1; + } + ans += (r - l + 1) as i32; } - let mut res = 0; - let mut product = 1; - let mut i = 0; - nums.iter().enumerate().for_each(|(j, v)| { - product *= v; - while product >= k { - product /= nums[i]; - i += 1; - } - res += j - i + 1; - }); - res as i32 + ans } } ``` @@ -175,14 +188,13 @@ impl Solution { */ var numSubarrayProductLessThanK = function (nums, k) { const n = nums.length; - let ans = 0; - let s = 1; - for (let i = 0, j = 0; i < n; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s = Math.floor(s / nums[j++]); + let [ans, l, p] = [0, 0, 1]; + for (let r = 0; r < n; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; }; @@ -193,17 +205,39 @@ var numSubarrayProductLessThanK = function (nums, k) { ```kotlin class Solution { fun numSubarrayProductLessThanK(nums: IntArray, k: Int): Int { - var left = 0 - var count = 0 - var product = 1 - nums.forEachIndexed { right, num -> - product *= num - while (product >= k && left <= right) { - product /= nums[left++] + var ans = 0 + var l = 0 + var p = 1 + + for (r in nums.indices) { + p *= nums[r] + while (l <= r && p >= k) { + p /= nums[l] + l++ } - count += right - left + 1 + ans += r - l + 1 } - return count + + return ans + } +} +``` + +#### C# + +```cs +public class Solution { + public int NumSubarrayProductLessThanK(int[] nums, int k) { + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.Length; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; + } + ans += r - l + 1; + } + return ans; } } ``` diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cpp b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cpp index 0052306036dec..2a15d2a5c7aba 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cpp +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cpp @@ -1,12 +1,15 @@ class Solution { public: int numSubarrayProductLessThanK(vector& nums, int k) { - int ans = 0; - for (int i = 0, j = 0, s = 1; i < nums.size(); ++i) { - s *= nums[i]; - while (j <= i && s >= k) s /= nums[j++]; - ans += i - j + 1; + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.size(); ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; + } + ans += r - l + 1; } return ans; } -}; \ No newline at end of file +}; diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cs b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cs new file mode 100644 index 0000000000000..786859514d1d1 --- /dev/null +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.cs @@ -0,0 +1,14 @@ +public class Solution { + public int NumSubarrayProductLessThanK(int[] nums, int k) { + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.Length; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; + } + ans += r - l + 1; + } + return ans; + } +} diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.go b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.go index 308553a88e0e8..6ec85c21f49bf 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.go +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.go @@ -1,11 +1,12 @@ -func numSubarrayProductLessThanK(nums []int, k int) int { - ans := 0 - for i, j, s := 0, 0, 1; i < len(nums); i++ { - s *= nums[i] - for ; j <= i && s >= k; j++ { - s /= nums[j] - } - ans += i - j + 1 - } - return ans -} \ No newline at end of file +func numSubarrayProductLessThanK(nums []int, k int) (ans int) { + l, p := 0, 1 + for r, x := range nums { + p *= x + for l <= r && p >= k { + p /= nums[l] + l++ + } + ans += r - l + 1 + } + return +} diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.java b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.java index 25a392ef755d0..c7efbc1f0e4ca 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.java +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.java @@ -1,13 +1,14 @@ class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { - int ans = 0; - for (int i = 0, j = 0, s = 1; i < nums.length; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s /= nums[j++]; + int ans = 0, l = 0; + int p = 1; + for (int r = 0; r < nums.length; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; } -} \ No newline at end of file +} diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.js b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.js index 3fc94b0a5559c..1925471f1b697 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.js +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.js @@ -5,14 +5,13 @@ */ var numSubarrayProductLessThanK = function (nums, k) { const n = nums.length; - let ans = 0; - let s = 1; - for (let i = 0, j = 0; i < n; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s = Math.floor(s / nums[j++]); + let [ans, l, p] = [0, 0, 1]; + for (let r = 0; r < n; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; }; diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.kt b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.kt index f91c0fc35afb9..97c3b09a16ca9 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.kt +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.kt @@ -1,15 +1,18 @@ class Solution { fun numSubarrayProductLessThanK(nums: IntArray, k: Int): Int { - var left = 0 - var count = 0 - var product = 1 - nums.forEachIndexed { right, num -> - product *= num - while (product >= k && left <= right) { - product /= nums[left++] + var ans = 0 + var l = 0 + var p = 1 + + for (r in nums.indices) { + p *= nums[r] + while (l <= r && p >= k) { + p /= nums[l] + l++ } - count += right - left + 1 + ans += r - l + 1 } - return count + + return ans } } diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.py b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.py index 679f7f50403b7..4289ebcb33fff 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.py +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.py @@ -1,10 +1,11 @@ class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: - ans, s, j = 0, 1, 0 - for i, v in enumerate(nums): - s *= v - while j <= i and s >= k: - s //= nums[j] - j += 1 - ans += i - j + 1 + ans = l = 0 + p = 1 + for r, x in enumerate(nums): + p *= x + while l <= r and p >= k: + p //= nums[l] + l += 1 + ans += r - l + 1 return ans diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.rs b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.rs index 4514c5f215eee..4629b0faff27e 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.rs +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.rs @@ -1,20 +1,18 @@ impl Solution { pub fn num_subarray_product_less_than_k(nums: Vec, k: i32) -> i32 { - if k <= 1 { - return 0; - } + let mut ans = 0; + let mut l = 0; + let mut p = 1; - let mut res = 0; - let mut product = 1; - let mut i = 0; - nums.iter().enumerate().for_each(|(j, v)| { - product *= v; - while product >= k { - product /= nums[i]; - i += 1; + for (r, &x) in nums.iter().enumerate() { + p *= x; + while l <= r && p >= k { + p /= nums[l]; + l += 1; } - res += j - i + 1; - }); - res as i32 + ans += (r - l + 1) as i32; + } + + ans } } diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.ts b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.ts index 658ad00e52b48..c4dd2a385f4e8 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/Solution.ts +++ b/solution/0700-0799/0713.Subarray Product Less Than K/Solution.ts @@ -1,11 +1,12 @@ function numSubarrayProductLessThanK(nums: number[], k: number): number { - let ans = 0; - for (let i = 0, j = 0, s = 1; i < nums.length; ++i) { - s *= nums[i]; - while (j <= i && s >= k) { - s /= nums[j++]; + const n = nums.length; + let [ans, l, p] = [0, 0, 1]; + for (let r = 0; r < n; ++r) { + p *= nums[r]; + while (l <= r && p >= k) { + p /= nums[l++]; } - ans += i - j + 1; + ans += r - l + 1; } return ans; } diff --git a/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/README.md b/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/README.md index ae649c2a8725f..3bd4713422b1f 100644 --- a/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/README.md +++ b/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/README.md @@ -246,6 +246,44 @@ function minimumSubarrayLength(nums: number[], k: number): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn minimum_subarray_length(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut cnt = vec![0; 32]; + let mut ans = n as i32 + 1; + let mut s = 0; + let mut i = 0; + + for (j, &x) in nums.iter().enumerate() { + s |= x; + for h in 0..32 { + if (x >> h) & 1 == 1 { + cnt[h] += 1; + } + } + + while s >= k && i <= j { + ans = ans.min((j - i + 1) as i32); + let y = nums[i]; + for h in 0..32 { + if (y >> h) & 1 == 1 { + cnt[h] -= 1; + if cnt[h] == 0 { + s ^= 1 << h; + } + } + } + i += 1; + } + } + if ans > n as i32 { -1 } else { ans } + } +} +``` + diff --git a/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/README_EN.md b/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/README_EN.md index 8c710f1b490d9..c0945b23bf163 100644 --- a/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/README_EN.md +++ b/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/README_EN.md @@ -244,6 +244,44 @@ function minimumSubarrayLength(nums: number[], k: number): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn minimum_subarray_length(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut cnt = vec![0; 32]; + let mut ans = n as i32 + 1; + let mut s = 0; + let mut i = 0; + + for (j, &x) in nums.iter().enumerate() { + s |= x; + for h in 0..32 { + if (x >> h) & 1 == 1 { + cnt[h] += 1; + } + } + + while s >= k && i <= j { + ans = ans.min((j - i + 1) as i32); + let y = nums[i]; + for h in 0..32 { + if (y >> h) & 1 == 1 { + cnt[h] -= 1; + if cnt[h] == 0 { + s ^= 1 << h; + } + } + } + i += 1; + } + } + if ans > n as i32 { -1 } else { ans } + } +} +``` + diff --git a/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/Solution.rs b/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/Solution.rs new file mode 100644 index 0000000000000..6c1529fe614b4 --- /dev/null +++ b/solution/3000-3099/3095.Shortest Subarray With OR at Least K I/Solution.rs @@ -0,0 +1,37 @@ +impl Solution { + pub fn minimum_subarray_length(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut cnt = vec![0; 32]; + let mut ans = n as i32 + 1; + let mut s = 0; + let mut i = 0; + + for (j, &x) in nums.iter().enumerate() { + s |= x; + for h in 0..32 { + if (x >> h) & 1 == 1 { + cnt[h] += 1; + } + } + + while s >= k && i <= j { + ans = ans.min((j - i + 1) as i32); + let y = nums[i]; + for h in 0..32 { + if (y >> h) & 1 == 1 { + cnt[h] -= 1; + if cnt[h] == 0 { + s ^= 1 << h; + } + } + } + i += 1; + } + } + if ans > n as i32 { + -1 + } else { + ans + } + } +} diff --git a/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/README.md b/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/README.md index d059a36144dd9..071641c8bdb7a 100644 --- a/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/README.md +++ b/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/README.md @@ -248,6 +248,44 @@ function minimumSubarrayLength(nums: number[], k: number): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn minimum_subarray_length(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut cnt = vec![0; 32]; + let mut ans = n as i32 + 1; + let mut s = 0; + let mut i = 0; + + for (j, &x) in nums.iter().enumerate() { + s |= x; + for h in 0..32 { + if (x >> h) & 1 == 1 { + cnt[h] += 1; + } + } + + while s >= k && i <= j { + ans = ans.min((j - i + 1) as i32); + let y = nums[i]; + for h in 0..32 { + if (y >> h) & 1 == 1 { + cnt[h] -= 1; + if cnt[h] == 0 { + s ^= 1 << h; + } + } + } + i += 1; + } + } + if ans > n as i32 { -1 } else { ans } + } +} +``` + diff --git a/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/README_EN.md b/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/README_EN.md index 5ccced4140e6c..fb9a7a251ef75 100644 --- a/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/README_EN.md +++ b/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/README_EN.md @@ -246,6 +246,44 @@ function minimumSubarrayLength(nums: number[], k: number): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn minimum_subarray_length(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut cnt = vec![0; 32]; + let mut ans = n as i32 + 1; + let mut s = 0; + let mut i = 0; + + for (j, &x) in nums.iter().enumerate() { + s |= x; + for h in 0..32 { + if (x >> h) & 1 == 1 { + cnt[h] += 1; + } + } + + while s >= k && i <= j { + ans = ans.min((j - i + 1) as i32); + let y = nums[i]; + for h in 0..32 { + if (y >> h) & 1 == 1 { + cnt[h] -= 1; + if cnt[h] == 0 { + s ^= 1 << h; + } + } + } + i += 1; + } + } + if ans > n as i32 { -1 } else { ans } + } +} +``` + diff --git a/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/Solution.rs b/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/Solution.rs new file mode 100644 index 0000000000000..6c1529fe614b4 --- /dev/null +++ b/solution/3000-3099/3097.Shortest Subarray With OR at Least K II/Solution.rs @@ -0,0 +1,37 @@ +impl Solution { + pub fn minimum_subarray_length(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut cnt = vec![0; 32]; + let mut ans = n as i32 + 1; + let mut s = 0; + let mut i = 0; + + for (j, &x) in nums.iter().enumerate() { + s |= x; + for h in 0..32 { + if (x >> h) & 1 == 1 { + cnt[h] += 1; + } + } + + while s >= k && i <= j { + ans = ans.min((j - i + 1) as i32); + let y = nums[i]; + for h in 0..32 { + if (y >> h) & 1 == 1 { + cnt[h] -= 1; + if cnt[h] == 0 { + s ^= 1 << h; + } + } + } + i += 1; + } + } + if ans > n as i32 { + -1 + } else { + ans + } + } +} From 94b04b7aa228910cd0798cac37e5db8c334df205 Mon Sep 17 00:00:00 2001 From: Libin YANG Date: Thu, 16 Jan 2025 10:00:26 +0800 Subject: [PATCH 2/2] feat: add solutions to lc problem: No.3422 (#3956) No.3422.Minimum Operations to Make Subarray Elements Equal --- .../README.md | 224 ++++++++++++++++++ .../README_EN.md | 224 ++++++++++++++++++ .../Solution.cpp | 36 +++ .../Solution.java | 52 ++++ .../Solution.py | 28 +++ solution/README.md | 1 + solution/README_EN.md | 1 + 7 files changed, 566 insertions(+) create mode 100644 solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/README.md create mode 100644 solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/README_EN.md create mode 100644 solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.cpp create mode 100644 solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.java create mode 100644 solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.py diff --git a/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/README.md b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/README.md new file mode 100644 index 0000000000000..063c164ac9244 --- /dev/null +++ b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/README.md @@ -0,0 +1,224 @@ +--- +comments: true +difficulty: 中等 +edit_url: https://github.com/doocs/leetcode/edit/main/solution/3400-3499/3422.Minimum%20Operations%20to%20Make%20Subarray%20Elements%20Equal/README.md +--- + + + +# [3422. Minimum Operations to Make Subarray Elements Equal 🔒](https://leetcode.cn/problems/minimum-operations-to-make-subarray-elements-equal) + +[English Version](/solution/3400-3499/3422.Minimum%20Operations%20to%20Make%20Subarray%20Elements%20Equal/README_EN.md) + +## 题目描述 + + + +

You are given an integer array nums and an integer k. You can perform the following operation any number of times:

+ +
    +
  • Increase or decrease any element of nums by 1.
  • +
+ +

Return the minimum number of operations required to ensure that at least one subarray of size k in nums has all elements equal.

+ +

 

+

Example 1:

+ +
+

Input: nums = [4,-3,2,1,-4,6], k = 3

+ +

Output: 5

+ +

Explanation:

+ +
    +
  • Use 4 operations to add 4 to nums[1]. The resulting array is [4, 1, 2, 1, -4, 6].
  • +
  • Use 1 operation to subtract 1 from nums[2]. The resulting array is [4, 1, 1, 1, -4, 6].
  • +
  • The array now contains a subarray [1, 1, 1] of size k = 3 with all elements equal. Hence, the answer is 5.
  • +
+
+ +

Example 2:

+ +
+

Input: nums = [-2,-2,3,1,4], k = 2

+ +

Output: 0

+ +

Explanation:

+ +
    +
  • +

    The subarray [-2, -2] of size k = 2 already contains all equal elements, so no operations are needed. Hence, the answer is 0.

    +
  • +
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • -106 <= nums[i] <= 106
  • +
  • 2 <= k <= nums.length
  • +
+ + + +## 解法 + + + +### 方法一:有序集合 + +根据题目描述,我们需要找到一个长度为 $k$ 的子数组,通过最少的操作使得子数组中的所有元素相等,即我们需要找到一个长度为 $k$ 的子数组,使得子数组中所有元素变成这 $k$ 个元素的中位数所需的最少操作次数最小。 + +我们可以使用两个有序集合 $l$ 和 $r$ 分别维护 $k$ 个元素的左右两部分,其中 $l$ 用于存储 $k$ 个元素中较小的一部分,$r$ 用于存储 $k$ 个元素中较大的一部分,并且 $l$ 的元素个数要么等于 $r$ 的元素个数,要么比 $r$ 的元素个数少一个,这样 $r$ 的最小值就是 $k$ 个元素中的中位数。 + +时间复杂度 $O(n \times \log k)$,空间复杂度 $O(k)$。其中 $n$ 为数组 $\textit{nums}$ 的长度。 + + + +#### Python3 + +```python +class Solution: + def minOperations(self, nums: List[int], k: int) -> int: + l = SortedList() + r = SortedList() + s1 = s2 = 0 + ans = inf + for i, x in enumerate(nums): + l.add(x) + s1 += x + y = l.pop() + s1 -= y + r.add(y) + s2 += y + if len(r) - len(l) > 1: + y = r.pop(0) + s2 -= y + l.add(y) + s1 += y + if i >= k - 1: + ans = min(ans, s2 - r[0] * len(r) + r[0] * len(l) - s1) + j = i - k + 1 + if nums[j] in r: + r.remove(nums[j]) + s2 -= nums[j] + else: + l.remove(nums[j]) + s1 -= nums[j] + return ans +``` + +#### Java + +```java +class Solution { + public long minOperations(int[] nums, int k) { + TreeMap l = new TreeMap<>(); + TreeMap r = new TreeMap<>(); + long s1 = 0, s2 = 0; + int sz1 = 0, sz2 = 0; + long ans = Long.MAX_VALUE; + for (int i = 0; i < nums.length; ++i) { + l.merge(nums[i], 1, Integer::sum); + s1 += nums[i]; + ++sz1; + int y = l.lastKey(); + if (l.merge(y, -1, Integer::sum) == 0) { + l.remove(y); + } + s1 -= y; + --sz1; + r.merge(y, 1, Integer::sum); + s2 += y; + ++sz2; + if (sz2 - sz1 > 1) { + y = r.firstKey(); + if (r.merge(y, -1, Integer::sum) == 0) { + r.remove(y); + } + s2 -= y; + --sz2; + l.merge(y, 1, Integer::sum); + s1 += y; + ++sz1; + } + if (i >= k - 1) { + ans = Math.min(ans, s2 - r.firstKey() * sz2 + r.firstKey() * sz1 - s1); + int j = i - k + 1; + if (r.containsKey(nums[j])) { + if (r.merge(nums[j], -1, Integer::sum) == 0) { + r.remove(nums[j]); + } + s2 -= nums[j]; + --sz2; + } else { + if (l.merge(nums[j], -1, Integer::sum) == 0) { + l.remove(nums[j]); + } + s1 -= nums[j]; + --sz1; + } + } + } + return ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + long long minOperations(vector& nums, int k) { + multiset l, r; + long long s1 = 0, s2 = 0, ans = 1e18; + for (int i = 0; i < nums.size(); ++i) { + l.insert(nums[i]); + s1 += nums[i]; + int y = *l.rbegin(); + l.erase(l.find(y)); + s1 -= y; + r.insert(y); + s2 += y; + if (r.size() - l.size() > 1) { + y = *r.begin(); + r.erase(r.find(y)); + s2 -= y; + l.insert(y); + s1 += y; + } + if (i >= k - 1) { + long long x = *r.begin(); + ans = min(ans, s2 - x * (int) r.size() + x * (int) l.size() - s1); + int j = i - k + 1; + if (r.contains(nums[j])) { + r.erase(r.find(nums[j])); + s2 -= nums[j]; + } else { + l.erase(l.find(nums[j])); + s1 -= nums[j]; + } + } + } + return ans; + } +}; +``` + +#### Go + +```go + +``` + + + + + + diff --git a/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/README_EN.md b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/README_EN.md new file mode 100644 index 0000000000000..4b0ce044bf85b --- /dev/null +++ b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/README_EN.md @@ -0,0 +1,224 @@ +--- +comments: true +difficulty: Medium +edit_url: https://github.com/doocs/leetcode/edit/main/solution/3400-3499/3422.Minimum%20Operations%20to%20Make%20Subarray%20Elements%20Equal/README_EN.md +--- + + + +# [3422. Minimum Operations to Make Subarray Elements Equal 🔒](https://leetcode.com/problems/minimum-operations-to-make-subarray-elements-equal) + +[中文文档](/solution/3400-3499/3422.Minimum%20Operations%20to%20Make%20Subarray%20Elements%20Equal/README.md) + +## Description + + + +

You are given an integer array nums and an integer k. You can perform the following operation any number of times:

+ +
    +
  • Increase or decrease any element of nums by 1.
  • +
+ +

Return the minimum number of operations required to ensure that at least one subarray of size k in nums has all elements equal.

+ +

 

+

Example 1:

+ +
+

Input: nums = [4,-3,2,1,-4,6], k = 3

+ +

Output: 5

+ +

Explanation:

+ +
    +
  • Use 4 operations to add 4 to nums[1]. The resulting array is [4, 1, 2, 1, -4, 6].
  • +
  • Use 1 operation to subtract 1 from nums[2]. The resulting array is [4, 1, 1, 1, -4, 6].
  • +
  • The array now contains a subarray [1, 1, 1] of size k = 3 with all elements equal. Hence, the answer is 5.
  • +
+
+ +

Example 2:

+ +
+

Input: nums = [-2,-2,3,1,4], k = 2

+ +

Output: 0

+ +

Explanation:

+ +
    +
  • +

    The subarray [-2, -2] of size k = 2 already contains all equal elements, so no operations are needed. Hence, the answer is 0.

    +
  • +
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • -106 <= nums[i] <= 106
  • +
  • 2 <= k <= nums.length
  • +
+ + + +## Solutions + + + +### Solution 1: Ordered Set + +According to the problem description, we need to find a subarray of length $k$ and make all elements in the subarray equal with the minimum number of operations. That is, we need to find a subarray of length $k$ such that the minimum number of operations required to make all elements in the subarray equal to the median of these $k$ elements is minimized. + +We can use two ordered sets $l$ and $r$ to maintain the left and right parts of the $k$ elements, respectively. $l$ is used to store the smaller part of the $k$ elements, and $r$ is used to store the larger part of the $k$ elements. The number of elements in $l$ is either equal to the number of elements in $r$ or one less than the number of elements in $r$, so the minimum value in $r$ is the median of the $k$ elements. + +The time complexity is $O(n \times \log k)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array $\textit{nums}$. + + + +#### Python3 + +```python +class Solution: + def minOperations(self, nums: List[int], k: int) -> int: + l = SortedList() + r = SortedList() + s1 = s2 = 0 + ans = inf + for i, x in enumerate(nums): + l.add(x) + s1 += x + y = l.pop() + s1 -= y + r.add(y) + s2 += y + if len(r) - len(l) > 1: + y = r.pop(0) + s2 -= y + l.add(y) + s1 += y + if i >= k - 1: + ans = min(ans, s2 - r[0] * len(r) + r[0] * len(l) - s1) + j = i - k + 1 + if nums[j] in r: + r.remove(nums[j]) + s2 -= nums[j] + else: + l.remove(nums[j]) + s1 -= nums[j] + return ans +``` + +#### Java + +```java +class Solution { + public long minOperations(int[] nums, int k) { + TreeMap l = new TreeMap<>(); + TreeMap r = new TreeMap<>(); + long s1 = 0, s2 = 0; + int sz1 = 0, sz2 = 0; + long ans = Long.MAX_VALUE; + for (int i = 0; i < nums.length; ++i) { + l.merge(nums[i], 1, Integer::sum); + s1 += nums[i]; + ++sz1; + int y = l.lastKey(); + if (l.merge(y, -1, Integer::sum) == 0) { + l.remove(y); + } + s1 -= y; + --sz1; + r.merge(y, 1, Integer::sum); + s2 += y; + ++sz2; + if (sz2 - sz1 > 1) { + y = r.firstKey(); + if (r.merge(y, -1, Integer::sum) == 0) { + r.remove(y); + } + s2 -= y; + --sz2; + l.merge(y, 1, Integer::sum); + s1 += y; + ++sz1; + } + if (i >= k - 1) { + ans = Math.min(ans, s2 - r.firstKey() * sz2 + r.firstKey() * sz1 - s1); + int j = i - k + 1; + if (r.containsKey(nums[j])) { + if (r.merge(nums[j], -1, Integer::sum) == 0) { + r.remove(nums[j]); + } + s2 -= nums[j]; + --sz2; + } else { + if (l.merge(nums[j], -1, Integer::sum) == 0) { + l.remove(nums[j]); + } + s1 -= nums[j]; + --sz1; + } + } + } + return ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + long long minOperations(vector& nums, int k) { + multiset l, r; + long long s1 = 0, s2 = 0, ans = 1e18; + for (int i = 0; i < nums.size(); ++i) { + l.insert(nums[i]); + s1 += nums[i]; + int y = *l.rbegin(); + l.erase(l.find(y)); + s1 -= y; + r.insert(y); + s2 += y; + if (r.size() - l.size() > 1) { + y = *r.begin(); + r.erase(r.find(y)); + s2 -= y; + l.insert(y); + s1 += y; + } + if (i >= k - 1) { + long long x = *r.begin(); + ans = min(ans, s2 - x * (int) r.size() + x * (int) l.size() - s1); + int j = i - k + 1; + if (r.contains(nums[j])) { + r.erase(r.find(nums[j])); + s2 -= nums[j]; + } else { + l.erase(l.find(nums[j])); + s1 -= nums[j]; + } + } + } + return ans; + } +}; +``` + +#### Go + +```go + +``` + + + + + + diff --git a/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.cpp b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.cpp new file mode 100644 index 0000000000000..7bb9e1937544c --- /dev/null +++ b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + long long minOperations(vector& nums, int k) { + multiset l, r; + long long s1 = 0, s2 = 0, ans = 1e18; + for (int i = 0; i < nums.size(); ++i) { + l.insert(nums[i]); + s1 += nums[i]; + int y = *l.rbegin(); + l.erase(l.find(y)); + s1 -= y; + r.insert(y); + s2 += y; + if (r.size() - l.size() > 1) { + y = *r.begin(); + r.erase(r.find(y)); + s2 -= y; + l.insert(y); + s1 += y; + } + if (i >= k - 1) { + long long x = *r.begin(); + ans = min(ans, s2 - x * (int) r.size() + x * (int) l.size() - s1); + int j = i - k + 1; + if (r.contains(nums[j])) { + r.erase(r.find(nums[j])); + s2 -= nums[j]; + } else { + l.erase(l.find(nums[j])); + s1 -= nums[j]; + } + } + } + return ans; + } +}; diff --git a/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.java b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.java new file mode 100644 index 0000000000000..e5a4ac7db28af --- /dev/null +++ b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.java @@ -0,0 +1,52 @@ +class Solution { + public long minOperations(int[] nums, int k) { + TreeMap l = new TreeMap<>(); + TreeMap r = new TreeMap<>(); + long s1 = 0, s2 = 0; + int sz1 = 0, sz2 = 0; + long ans = Long.MAX_VALUE; + for (int i = 0; i < nums.length; ++i) { + l.merge(nums[i], 1, Integer::sum); + s1 += nums[i]; + ++sz1; + int y = l.lastKey(); + if (l.merge(y, -1, Integer::sum) == 0) { + l.remove(y); + } + s1 -= y; + --sz1; + r.merge(y, 1, Integer::sum); + s2 += y; + ++sz2; + if (sz2 - sz1 > 1) { + y = r.firstKey(); + if (r.merge(y, -1, Integer::sum) == 0) { + r.remove(y); + } + s2 -= y; + --sz2; + l.merge(y, 1, Integer::sum); + s1 += y; + ++sz1; + } + if (i >= k - 1) { + ans = Math.min(ans, s2 - r.firstKey() * sz2 + r.firstKey() * sz1 - s1); + int j = i - k + 1; + if (r.containsKey(nums[j])) { + if (r.merge(nums[j], -1, Integer::sum) == 0) { + r.remove(nums[j]); + } + s2 -= nums[j]; + --sz2; + } else { + if (l.merge(nums[j], -1, Integer::sum) == 0) { + l.remove(nums[j]); + } + s1 -= nums[j]; + --sz1; + } + } + } + return ans; + } +} diff --git a/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.py b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.py new file mode 100644 index 0000000000000..4067339eacb37 --- /dev/null +++ b/solution/3400-3499/3422.Minimum Operations to Make Subarray Elements Equal/Solution.py @@ -0,0 +1,28 @@ +class Solution: + def minOperations(self, nums: List[int], k: int) -> int: + l = SortedList() + r = SortedList() + s1 = s2 = 0 + ans = inf + for i, x in enumerate(nums): + l.add(x) + s1 += x + y = l.pop() + s1 -= y + r.add(y) + s2 += y + if len(r) - len(l) > 1: + y = r.pop(0) + s2 -= y + l.add(y) + s1 += y + if i >= k - 1: + ans = min(ans, s2 - r[0] * len(r) + r[0] * len(l) - s1) + j = i - k + 1 + if nums[j] in r: + r.remove(nums[j]) + s2 -= nums[j] + else: + l.remove(nums[j]) + s1 -= nums[j] + return ans diff --git a/solution/README.md b/solution/README.md index 908e0f42f3d20..9e5e9333ca9a2 100644 --- a/solution/README.md +++ b/solution/README.md @@ -3432,6 +3432,7 @@ | 3419 | [图的最大边权的最小值](/solution/3400-3499/3419.Minimize%20the%20Maximum%20Edge%20Weight%20of%20Graph/README.md) | | 中等 | 第 432 场周赛 | | 3420 | [统计 K 次操作以内得到非递减子数组的数目](/solution/3400-3499/3420.Count%20Non-Decreasing%20Subarrays%20After%20K%20Operations/README.md) | | 困难 | 第 432 场周赛 | | 3421 | [查找进步的学生](/solution/3400-3499/3421.Find%20Students%20Who%20Improved/README.md) | | 中等 | | +| 3422 | [Minimum Operations to Make Subarray Elements Equal](/solution/3400-3499/3422.Minimum%20Operations%20to%20Make%20Subarray%20Elements%20Equal/README.md) | | 中等 | 🔒 | ## 版权 diff --git a/solution/README_EN.md b/solution/README_EN.md index 6b3b052ba1a0c..8c913ea30f7bc 100644 --- a/solution/README_EN.md +++ b/solution/README_EN.md @@ -3430,6 +3430,7 @@ Press Control + F(or Command + F on | 3419 | [Minimize the Maximum Edge Weight of Graph](/solution/3400-3499/3419.Minimize%20the%20Maximum%20Edge%20Weight%20of%20Graph/README_EN.md) | | Medium | Weekly Contest 432 | | 3420 | [Count Non-Decreasing Subarrays After K Operations](/solution/3400-3499/3420.Count%20Non-Decreasing%20Subarrays%20After%20K%20Operations/README_EN.md) | | Hard | Weekly Contest 432 | | 3421 | [Find Students Who Improved](/solution/3400-3499/3421.Find%20Students%20Who%20Improved/README_EN.md) | | Medium | | +| 3422 | [Minimum Operations to Make Subarray Elements Equal](/solution/3400-3499/3422.Minimum%20Operations%20to%20Make%20Subarray%20Elements%20Equal/README_EN.md) | | Medium | 🔒 | ## Copyright