From c9e7bdb62a2fd1593e431c2f14324f68f799b529 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Sun, 2 Apr 2023 10:26:17 +0800 Subject: [PATCH 1/3] feat: add solutions to lc problems: No.2605~2608 * No.2605.Form Smallest Number From Two Digit Arrays * No.2606.Find the Substring With Maximum Cost * No.2607.Make K-Subarray Sums Equal * No.2608.Shortest Cycle in a Graph --- .../0789.Escape The Ghosts/README.md | 2 +- .../README_EN.md | 2 +- .../README.md | 134 +++++++++ .../README_EN.md | 126 +++++++++ .../Solution.cpp | 16 ++ .../Solution.go | 20 ++ .../Solution.java | 15 + .../Solution.py | 10 + .../README.md | 179 ++++++++++++ .../README_EN.md | 171 +++++++++++ .../Solution.cpp | 19 ++ .../Solution.go | 35 +++ .../Solution.java | 20 ++ .../Solution.py | 10 + .../2607.Make K-Subarray Sums Equal/README.md | 191 +++++++++++++ .../README_EN.md | 183 ++++++++++++ .../Solution.cpp | 25 ++ .../Solution.go | 33 +++ .../Solution.java | 28 ++ .../Solution.py | 13 + .../2608.Shortest Cycle in a Graph/README.md | 266 ++++++++++++++++++ .../README_EN.md | 258 +++++++++++++++++ .../Solution.cpp | 39 +++ .../Solution.go | 47 ++++ .../Solution.java | 41 +++ .../Solution.py | 22 ++ .../Solution.ts | 32 +++ .../images/cropped.png | Bin 0 -> 16687 bytes .../images/croppedagin.png | Bin 0 -> 9317 bytes solution/CONTEST_README.md | 10 +- solution/CONTEST_README_EN.md | 8 + solution/README.md | 4 + solution/README_EN.md | 4 + solution/summary.md | 4 + solution/summary_en.md | 4 + 35 files changed, 1968 insertions(+), 3 deletions(-) create mode 100644 solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md create mode 100644 solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md create mode 100644 solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.cpp create mode 100644 solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.go create mode 100644 solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.java create mode 100644 solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py create mode 100644 solution/2600-2699/2606.Find the Substring With Maximum Cost/README.md create mode 100644 solution/2600-2699/2606.Find the Substring With Maximum Cost/README_EN.md create mode 100644 solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.cpp create mode 100644 solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.go create mode 100644 solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.java create mode 100644 solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py create mode 100644 solution/2600-2699/2607.Make K-Subarray Sums Equal/README.md create mode 100644 solution/2600-2699/2607.Make K-Subarray Sums Equal/README_EN.md create mode 100644 solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.cpp create mode 100644 solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.go create mode 100644 solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.java create mode 100644 solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.py create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/README.md create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/README_EN.md create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.cpp create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.go create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.java create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.ts create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/images/cropped.png create mode 100644 solution/2600-2699/2608.Shortest Cycle in a Graph/images/croppedagin.png diff --git a/solution/0700-0799/0789.Escape The Ghosts/README.md b/solution/0700-0799/0789.Escape The Ghosts/README.md index 4b5cd3245f7d0..ab170bbb2f562 100644 --- a/solution/0700-0799/0789.Escape The Ghosts/README.md +++ b/solution/0700-0799/0789.Escape The Ghosts/README.md @@ -12,7 +12,7 @@

如果你可以在任何阻碍者抓住你 之前 到达目的地(阻碍者可以采取任意行动方式),则被视为逃脱成功。如果你和阻碍者 同时 到达了一个位置(包括目的地) 都不算 是逃脱成功。

-

只有在你有可能成功逃脱时,输出 true ;否则,输出 false

+

如果不管阻碍者怎么移动都可以成功逃脱时,输出 true ;否则,输出 false

 

示例 1:

diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md index d12812c16fe47..611f88cfd83d2 100644 --- a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md @@ -59,7 +59,7 @@ class Solution: if s[i] == s[j]: return dfs(i + 1, j - 1) return 1 + min(dfs(i + 1, j), dfs(i, j - 1)) - + return dfs(0, len(s) - 1) ``` diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md new file mode 100644 index 0000000000000..df5a95b0aeb3b --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md @@ -0,0 +1,134 @@ +# [2605. 从两个数字数组里生成最小数字](https://leetcode.cn/problems/form-smallest-number-from-two-digit-arrays) + +[English Version](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README_EN.md) + +## 题目描述 + + + +给你两个只包含 1 到 9 之间数字的数组 nums1 和 nums2 ,每个数组中的元素 互不相同 ,请你返回 最小 的数字,两个数组都 至少 包含这个数字的某个数位。 + +

 

+ +

示例 1:

+ +
输入:nums1 = [4,1,3], nums2 = [5,7]
+输出:15
+解释:数字 15 的数位 1 在 nums1 中出现,数位 5 在 nums2 中出现。15 是我们能得到的最小数字。
+
+ +

示例 2:

+ +
输入:nums1 = [3,5,2,6], nums2 = [3,1,7]
+输出:3
+解释:数字 3 的数位 3 在两个数组中都出现了。
+
+ +

 

+ +

提示:

+ + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + ans = 100 + for a in nums1: + for b in nums2: + if a == b: + ans = min(ans, a) + else: + ans = min(ans, 10 * a + b, 10 * b + a) + return ans +``` + +### **Java** + + + +```java +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = Math.min(ans, a); + } else { + ans = Math.min(ans, Math.min(a * 10 + b, b * 10 + a)); + } + } + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = min(ans, a); + } else { + ans = min({ans, a * 10 + b, b * 10 + a}); + } + } + } + return ans; + } +}; +``` + +### **Go** + +```go +func minNumber(nums1 []int, nums2 []int) int { + ans := 100 + for _, a := range nums1 { + for _, b := range nums2 { + if a == b { + ans = min(ans, a) + } else { + ans = min(ans, min(a*10+b, b*10+a)) + } + } + } + return ans +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md new file mode 100644 index 0000000000000..0fb48ae681a0a --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md @@ -0,0 +1,126 @@ +# [2605. Form Smallest Number From Two Digit Arrays](https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays) + +[中文文档](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README.md) + +## Description + +Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array. + +

 

+

Example 1:

+ +
+Input: nums1 = [4,1,3], nums2 = [5,7]
+Output: 15
+Explanation: The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have.
+
+ +

Example 2:

+ +
+Input: nums1 = [3,5,2,6], nums2 = [3,1,7]
+Output: 3
+Explanation: The number 3 contains the digit 3 which exists in both arrays.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 9
  • +
  • 1 <= nums1[i], nums2[i] <= 9
  • +
  • All digits in each array are unique.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + ans = 100 + for a in nums1: + for b in nums2: + if a == b: + ans = min(ans, a) + else: + ans = min(ans, 10 * a + b, 10 * b + a) + return ans +``` + +### **Java** + +```java +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = Math.min(ans, a); + } else { + ans = Math.min(ans, Math.min(a * 10 + b, b * 10 + a)); + } + } + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = min(ans, a); + } else { + ans = min({ans, a * 10 + b, b * 10 + a}); + } + } + } + return ans; + } +}; +``` + +### **Go** + +```go +func minNumber(nums1 []int, nums2 []int) int { + ans := 100 + for _, a := range nums1 { + for _, b := range nums2 { + if a == b { + ans = min(ans, a) + } else { + ans = min(ans, min(a*10+b, b*10+a)) + } + } + } + return ans +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.cpp b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.cpp new file mode 100644 index 0000000000000..0e5298d8239b3 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = min(ans, a); + } else { + ans = min({ans, a * 10 + b, b * 10 + a}); + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.go b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.go new file mode 100644 index 0000000000000..783e8a448c877 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.go @@ -0,0 +1,20 @@ +func minNumber(nums1 []int, nums2 []int) int { + ans := 100 + for _, a := range nums1 { + for _, b := range nums2 { + if a == b { + ans = min(ans, a) + } else { + ans = min(ans, min(a*10+b, b*10+a)) + } + } + } + return ans +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.java b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.java new file mode 100644 index 0000000000000..3fb58eeeeaa61 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.java @@ -0,0 +1,15 @@ +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = Math.min(ans, a); + } else { + ans = Math.min(ans, Math.min(a * 10 + b, b * 10 + a)); + } + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py new file mode 100644 index 0000000000000..46585c47d6975 --- /dev/null +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py @@ -0,0 +1,10 @@ +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + ans = 100 + for a in nums1: + for b in nums2: + if a == b: + ans = min(ans, a) + else: + ans = min(ans, 10 * a + b, 10 * b + a) + return ans diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/README.md b/solution/2600-2699/2606.Find the Substring With Maximum Cost/README.md new file mode 100644 index 0000000000000..c6c1edd3c503e --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/README.md @@ -0,0 +1,179 @@ +# [2606. 找到最大开销的子字符串](https://leetcode.cn/problems/find-the-substring-with-maximum-cost) + +[English Version](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README_EN.md) + +## 题目描述 + + + +

给你一个字符串 s ,一个字符 互不相同 的字符串 chars 和一个长度与 chars 相同的整数数组 vals 。

+ +

子字符串的开销 是一个子字符串中所有字符对应价值之和。空字符串的开销是 0 。

+ +

字符的价值 定义如下:

+ +
    +
  • 如果字符不在字符串 chars 中,那么它的价值是它在字母表中的位置(下标从 1 开始)。 +
      +
    • 比方说,'a' 的价值为 1 ,'b' 的价值为 2 ,以此类推,'z' 的价值为 26 。
    • +
    +
  • +
  • 否则,如果这个字符在 chars 中的位置为 i ,那么它的价值就是 vals[i] 。
  • +
+ +

请你返回字符串 s 的所有子字符串中的最大开销。

+ +

 

+ +

示例 1:

+ +
输入:s = "adaa", chars = "d", vals = [-1000]
+输出:2
+解释:字符 "a" 和 "d" 的价值分别为 1 和 -1000 。
+最大开销子字符串是 "aa" ,它的开销为 1 + 1 = 2 。
+2 是最大开销。
+
+ +

示例 2:

+ +
输入:s = "abc", chars = "abc", vals = [-1,-1,-1]
+输出:0
+解释:字符 "a" ,"b" 和 "c" 的价值分别为 -1 ,-1 和 -1 。
+最大开销子字符串是 "" ,它的开销为 0 。
+0 是最大开销。
+
+ +

 

+ +

提示:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s 只包含小写英文字母。
  • +
  • 1 <= chars.length <= 26
  • +
  • chars 只包含小写英文字母,且 互不相同 。
  • +
  • vals.length == chars.length
  • +
  • -1000 <= vals[i] <= 1000
  • +
+ +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: + d = {c: i for i, c in enumerate(chars)} + ans = tot = mi = 0 + for c in s: + v = vals[d[c]] if c in d else ord(c) - ord('a') + 1 + tot += v + ans = max(ans, tot - mi) + mi = min(mi, tot) + return ans +``` + +### **Java** + + + +```java +class Solution { + public int maximumCostSubstring(String s, String chars, int[] vals) { + int[] d = new int[26]; + Arrays.fill(d, -1); + int m = chars.length(); + for (int i = 0; i < m; ++i) { + d[chars.charAt(i) - 'a'] = i; + } + int ans = 0, tot = 0, mi = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + int j = s.charAt(i) - 'a'; + int v = d[j] == -1 ? j + 1 : vals[d[j]]; + tot += v; + ans = Math.max(ans, tot - mi); + mi = Math.min(mi, tot); + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maximumCostSubstring(string s, string chars, vector& vals) { + vector d(26, -1); + int m = chars.size(); + for (int i = 0; i < m; ++i) { + d[chars[i] - 'a'] = i; + } + int ans = 0, tot = 0, mi = 0; + for (char& c : s) { + int j = c - 'a'; + int v = d[j] == -1 ? j + 1 : vals[d[j]]; + tot += v; + ans = max(ans, tot - mi); + mi = min(mi, tot); + } + return ans; + } +}; +``` + +### **Go** + +```go +func maximumCostSubstring(s string, chars string, vals []int) (ans int) { + d := [26]int{} + for i := range d { + d[i] = -1 + } + for i, c := range chars { + d[c-'a'] = i + } + tot, mi := 0, 0 + for _, c := range s { + j := int(c - 'a') + v := j + 1 + if d[j] != -1 { + v = vals[d[j]] + } + tot += v + ans = max(ans, tot-mi) + mi = min(mi, tot) + } + return +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/README_EN.md b/solution/2600-2699/2606.Find the Substring With Maximum Cost/README_EN.md new file mode 100644 index 0000000000000..f4c29326a1930 --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/README_EN.md @@ -0,0 +1,171 @@ +# [2606. Find the Substring With Maximum Cost](https://leetcode.com/problems/find-the-substring-with-maximum-cost) + +[中文文档](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README.md) + +## Description + +

You are given a string s, a string chars of distinct characters and an integer array vals of the same length as chars.

+ +

The cost of the substring is the sum of the values of each character in the substring. The cost of an empty string is considered 0.

+ +

The value of the character is defined in the following way:

+ +
    +
  • If the character is not in the string chars, then its value is its corresponding position (1-indexed) in the alphabet. +
      +
    • For example, the value of 'a' is 1, the value of 'b' is 2, and so on. The value of 'z' is 26.
    • +
    +
  • +
  • Otherwise, assuming i is the index where the character occurs in the string chars, then its value is vals[i].
  • +
+ +

Return the maximum cost among all substrings of the string s.

+ +

 

+

Example 1:

+ +
+Input: s = "adaa", chars = "d", vals = [-1000]
+Output: 2
+Explanation: The value of the characters "a" and "d" is 1 and -1000 respectively.
+The substring with the maximum cost is "aa" and its cost is 1 + 1 = 2.
+It can be proven that 2 is the maximum cost.
+
+ +

Example 2:

+ +
+Input: s = "abc", chars = "abc", vals = [-1,-1,-1]
+Output: 0
+Explanation: The value of the characters "a", "b" and "c" is -1, -1, and -1 respectively.
+The substring with the maximum cost is the empty substring "" and its cost is 0.
+It can be proven that 0 is the maximum cost.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consist of lowercase English letters.
  • +
  • 1 <= chars.length <= 26
  • +
  • chars consist of distinct lowercase English letters.
  • +
  • vals.length == chars.length
  • +
  • -1000 <= vals[i] <= 1000
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: + d = {c: i for i, c in enumerate(chars)} + ans = tot = mi = 0 + for c in s: + v = vals[d[c]] if c in d else ord(c) - ord('a') + 1 + tot += v + ans = max(ans, tot - mi) + mi = min(mi, tot) + return ans +``` + +### **Java** + +```java +class Solution { + public int maximumCostSubstring(String s, String chars, int[] vals) { + int[] d = new int[26]; + Arrays.fill(d, -1); + int m = chars.length(); + for (int i = 0; i < m; ++i) { + d[chars.charAt(i) - 'a'] = i; + } + int ans = 0, tot = 0, mi = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + int j = s.charAt(i) - 'a'; + int v = d[j] == -1 ? j + 1 : vals[d[j]]; + tot += v; + ans = Math.max(ans, tot - mi); + mi = Math.min(mi, tot); + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maximumCostSubstring(string s, string chars, vector& vals) { + vector d(26, -1); + int m = chars.size(); + for (int i = 0; i < m; ++i) { + d[chars[i] - 'a'] = i; + } + int ans = 0, tot = 0, mi = 0; + for (char& c : s) { + int j = c - 'a'; + int v = d[j] == -1 ? j + 1 : vals[d[j]]; + tot += v; + ans = max(ans, tot - mi); + mi = min(mi, tot); + } + return ans; + } +}; +``` + +### **Go** + +```go +func maximumCostSubstring(s string, chars string, vals []int) (ans int) { + d := [26]int{} + for i := range d { + d[i] = -1 + } + for i, c := range chars { + d[c-'a'] = i + } + tot, mi := 0, 0 + for _, c := range s { + j := int(c - 'a') + v := j + 1 + if d[j] != -1 { + v = vals[d[j]] + } + tot += v + ans = max(ans, tot-mi) + mi = min(mi, tot) + } + return +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.cpp b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.cpp new file mode 100644 index 0000000000000..57962e1ad9400 --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maximumCostSubstring(string s, string chars, vector& vals) { + vector d(26, -1); + int m = chars.size(); + for (int i = 0; i < m; ++i) { + d[chars[i] - 'a'] = i; + } + int ans = 0, tot = 0, mi = 0; + for (char& c : s) { + int j = c - 'a'; + int v = d[j] == -1 ? j + 1 : vals[d[j]]; + tot += v; + ans = max(ans, tot - mi); + mi = min(mi, tot); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.go b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.go new file mode 100644 index 0000000000000..647772b312cd0 --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.go @@ -0,0 +1,35 @@ +func maximumCostSubstring(s string, chars string, vals []int) (ans int) { + d := [26]int{} + for i := range d { + d[i] = -1 + } + for i, c := range chars { + d[c-'a'] = i + } + tot, mi := 0, 0 + for _, c := range s { + j := int(c - 'a') + v := j + 1 + if d[j] != -1 { + v = vals[d[j]] + } + tot += v + ans = max(ans, tot-mi) + mi = min(mi, tot) + } + return +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} \ No newline at end of file diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.java b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.java new file mode 100644 index 0000000000000..1f027ce32ae7b --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.java @@ -0,0 +1,20 @@ +class Solution { + public int maximumCostSubstring(String s, String chars, int[] vals) { + int[] d = new int[26]; + Arrays.fill(d, -1); + int m = chars.length(); + for (int i = 0; i < m; ++i) { + d[chars.charAt(i) - 'a'] = i; + } + int ans = 0, tot = 0, mi = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + int j = s.charAt(i) - 'a'; + int v = d[j] == -1 ? j + 1 : vals[d[j]]; + tot += v; + ans = Math.max(ans, tot - mi); + mi = Math.min(mi, tot); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py new file mode 100644 index 0000000000000..ac13e9c91191e --- /dev/null +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py @@ -0,0 +1,10 @@ +class Solution: + def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: + d = {c: i for i, c in enumerate(chars)} + ans = tot = mi = 0 + for c in s: + v = vals[d[c]] if c in d else ord(c) - ord('a') + 1 + tot += v + ans = max(ans, tot - mi) + mi = min(mi, tot) + return ans diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/README.md b/solution/2600-2699/2607.Make K-Subarray Sums Equal/README.md new file mode 100644 index 0000000000000..fa9e720fb157f --- /dev/null +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/README.md @@ -0,0 +1,191 @@ +# [2607. 使子数组元素和相等](https://leetcode.cn/problems/make-k-subarray-sums-equal) + +[English Version](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README_EN.md) + +## 题目描述 + + + +

给你一个下标从 0 开始的整数数组 arr 和一个整数 k 。数组 arr 是一个循环数组。换句话说,数组中的最后一个元素的下一个元素是数组中的第一个元素,数组中第一个元素的前一个元素是数组中的最后一个元素。

+ +

你可以执行下述运算任意次:

+ +
    +
  • 选中 arr 中任意一个元素,并使其值加上 1 或减去 1
  • +
+ +

执行运算使每个长度为 k子数组 的元素总和都相等,返回所需要的最少运算次数。

+ +

子数组 是数组的一个连续部分。

+ +

 

+ +

示例 1:

+ +
输入:arr = [1,4,1,3], k = 2
+输出:1
+解释:在下标为 1 的元素那里执行一次运算,使其等于 3 。
+执行运算后,数组变为 [1,3,1,3] 。
+- 0 处起始的子数组为 [1, 3] ,元素总和为 4 
+- 1 处起始的子数组为 [3, 1] ,元素总和为 4 
+- 2 处起始的子数组为 [1, 3] ,元素总和为 4 
+- 3 处起始的子数组为 [3, 1] ,元素总和为 4 
+
+ +

示例 2:

+ +
输入:arr = [2,5,5,7], k = 3
+输出:5
+解释:在下标为 0 的元素那里执行三次运算,使其等于 5 。在下标为 3 的元素那里执行两次运算,使其等于 5 。
+执行运算后,数组变为 [5,5,5,5] 。
+- 0 处起始的子数组为 [5, 5, 5] ,元素总和为 15
+- 1 处起始的子数组为 [5, 5, 5] ,元素总和为 15
+- 2 处起始的子数组为 [5, 5, 5] ,元素总和为 15
+- 3 处起始的子数组为 [5, 5, 5] ,元素总和为 15
+
+ +

 

+ +

提示:

+ +
    +
  • 1 <= k <= arr.length <= 105
  • +
  • 1 <= arr[i] <= 109
  • +
+ +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def makeSubKSumEqual(self, arr: List[int], k: int) -> int: + n = len(arr) + if n == k: + return 0 + g = gcd(n, k) + ans = 0 + for i in range(g): + t = sorted(arr[j] for j in range(i, n, g)) + mid = t[len(t) >> 1] + s = sum(abs(x - mid) for x in t) + ans += s + return ans +``` + +### **Java** + + + +```java +class Solution { + public long makeSubKSumEqual(int[] arr, int k) { + int n = arr.length; + if (n == k) { + return 0; + } + int g = gcd(n, k); + long ans = 0; + for (int i = 0; i < g; ++i) { + List t = new ArrayList<>(); + for (int j = i; j < n; j += g) { + t.add(arr[j]); + } + t.sort((a, b) -> a - b); + int mid = t.get(t.size() >> 1); + long s = 0; + for (int x : t) { + s += Math.abs(x - mid); + } + ans += s; + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) { + int n = arr.size(); + if (n == k) { + return 0; + } + int g = gcd(n, k); + long long ans = 0; + for (int i = 0; i < g; ++i) { + vector t; + for (int j = i; j < n; j += g) { + t.push_back(arr[j]); + } + sort(t.begin(), t.end()); + int mid = t[t.size() / 2]; + long long s = 0; + for (int x : t) { + s += abs(x - mid); + } + ans += s; + } + return ans; + } +}; +``` + +### **Go** + +```go +func makeSubKSumEqual(arr []int, k int) (ans int64) { + n := len(arr) + if n == k { + return 0 + } + g := gcd(n, k) + for i := 0; i < g; i++ { + t := []int{} + for j := i; j < n; j += g { + t = append(t, arr[j]) + } + sort.Ints(t) + mid := t[len(t)/2] + for _, x := range t { + ans += int64(abs(x - mid)) + } + } + return +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +func gcd(a, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/README_EN.md b/solution/2600-2699/2607.Make K-Subarray Sums Equal/README_EN.md new file mode 100644 index 0000000000000..9571b09835411 --- /dev/null +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/README_EN.md @@ -0,0 +1,183 @@ +# [2607. Make K-Subarray Sums Equal](https://leetcode.com/problems/make-k-subarray-sums-equal) + +[中文文档](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README.md) + +## Description + +

You are given a 0-indexed integer array arr and an integer k. The array arr is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.

+ +

You can do the following operation any number of times:

+ +
    +
  • Pick any element from arr and increase or decrease it by 1.
  • +
+ +

Return the minimum number of operations such that the sum of each subarray of length k is equal.

+ +

A subarray is a contiguous part of the array.

+ +

 

+

Example 1:

+ +
+Input: arr = [1,4,1,3], k = 2
+Output: 1
+Explanation: we can do one operation on index 1 to make its value equal to 3.
+The array after the operation is [1,3,1,3]
+- Subarray starts at index 0 is [1, 3], and its sum is 4 
+- Subarray starts at index 1 is [3, 1], and its sum is 4 
+- Subarray starts at index 2 is [1, 3], and its sum is 4 
+- Subarray starts at index 3 is [3, 1], and its sum is 4 
+
+ +

Example 2:

+ +
+Input: arr = [2,5,5,7], k = 3
+Output: 5
+Explanation: we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5.
+The array after the operations is [5,5,5,5]
+- Subarray starts at index 0 is [5, 5, 5], and its sum is 15
+- Subarray starts at index 1 is [5, 5, 5], and its sum is 15
+- Subarray starts at index 2 is [5, 5, 5], and its sum is 15
+- Subarray starts at index 3 is [5, 5, 5], and its sum is 15 
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= arr.length <= 105
  • +
  • 1 <= arr[i] <= 109
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def makeSubKSumEqual(self, arr: List[int], k: int) -> int: + n = len(arr) + if n == k: + return 0 + g = gcd(n, k) + ans = 0 + for i in range(g): + t = sorted(arr[j] for j in range(i, n, g)) + mid = t[len(t) >> 1] + s = sum(abs(x - mid) for x in t) + ans += s + return ans +``` + +### **Java** + +```java +class Solution { + public long makeSubKSumEqual(int[] arr, int k) { + int n = arr.length; + if (n == k) { + return 0; + } + int g = gcd(n, k); + long ans = 0; + for (int i = 0; i < g; ++i) { + List t = new ArrayList<>(); + for (int j = i; j < n; j += g) { + t.add(arr[j]); + } + t.sort((a, b) -> a - b); + int mid = t.get(t.size() >> 1); + long s = 0; + for (int x : t) { + s += Math.abs(x - mid); + } + ans += s; + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) { + int n = arr.size(); + if (n == k) { + return 0; + } + int g = gcd(n, k); + long long ans = 0; + for (int i = 0; i < g; ++i) { + vector t; + for (int j = i; j < n; j += g) { + t.push_back(arr[j]); + } + sort(t.begin(), t.end()); + int mid = t[t.size() / 2]; + long long s = 0; + for (int x : t) { + s += abs(x - mid); + } + ans += s; + } + return ans; + } +}; +``` + +### **Go** + +```go +func makeSubKSumEqual(arr []int, k int) (ans int64) { + n := len(arr) + if n == k { + return 0 + } + g := gcd(n, k) + for i := 0; i < g; i++ { + t := []int{} + for j := i; j < n; j += g { + t = append(t, arr[j]) + } + sort.Ints(t) + mid := t[len(t)/2] + for _, x := range t { + ans += int64(abs(x - mid)) + } + } + return +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +func gcd(a, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.cpp b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.cpp new file mode 100644 index 0000000000000..51ab0479a7264 --- /dev/null +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) { + int n = arr.size(); + if (n == k) { + return 0; + } + int g = gcd(n, k); + long long ans = 0; + for (int i = 0; i < g; ++i) { + vector t; + for (int j = i; j < n; j += g) { + t.push_back(arr[j]); + } + sort(t.begin(), t.end()); + int mid = t[t.size() / 2]; + long long s = 0; + for (int x : t) { + s += abs(x - mid); + } + ans += s; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.go b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.go new file mode 100644 index 0000000000000..e02042ad1a776 --- /dev/null +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.go @@ -0,0 +1,33 @@ +func makeSubKSumEqual(arr []int, k int) (ans int64) { + n := len(arr) + if n == k { + return 0 + } + g := gcd(n, k) + for i := 0; i < g; i++ { + t := []int{} + for j := i; j < n; j += g { + t = append(t, arr[j]) + } + sort.Ints(t) + mid := t[len(t)/2] + for _, x := range t { + ans += int64(abs(x - mid)) + } + } + return +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +func gcd(a, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} \ No newline at end of file diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.java b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.java new file mode 100644 index 0000000000000..2fdf04bd73a69 --- /dev/null +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.java @@ -0,0 +1,28 @@ +class Solution { + public long makeSubKSumEqual(int[] arr, int k) { + int n = arr.length; + if (n == k) { + return 0; + } + int g = gcd(n, k); + long ans = 0; + for (int i = 0; i < g; ++i) { + List t = new ArrayList<>(); + for (int j = i; j < n; j += g) { + t.add(arr[j]); + } + t.sort((a, b) -> a - b); + int mid = t.get(t.size() >> 1); + long s = 0; + for (int x : t) { + s += Math.abs(x - mid); + } + ans += s; + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} \ No newline at end of file diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.py b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.py new file mode 100644 index 0000000000000..b27c22b5e7db9 --- /dev/null +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/Solution.py @@ -0,0 +1,13 @@ +class Solution: + def makeSubKSumEqual(self, arr: List[int], k: int) -> int: + n = len(arr) + if n == k: + return 0 + g = gcd(n, k) + ans = 0 + for i in range(g): + t = sorted(arr[j] for j in range(i, n, g)) + mid = t[len(t) >> 1] + s = sum(abs(x - mid) for x in t) + ans += s + return ans diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/README.md b/solution/2600-2699/2608.Shortest Cycle in a Graph/README.md new file mode 100644 index 0000000000000..e4de747bf1874 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/README.md @@ -0,0 +1,266 @@ +# [2608. 图中的最短环](https://leetcode.cn/problems/shortest-cycle-in-a-graph) + +[English Version](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README_EN.md) + +## 题目描述 + + + +

现有一个含 n 个顶点的 双向 图,每个顶点按从 0n - 1 标记。图中的边由二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 uivi 之间存在一条边。每对顶点最多通过一条边连接,并且不存在与自身相连的顶点。

+ +

返回图中 最短 环的长度。如果不存在环,则返回 -1

+ +

是指以同一节点开始和结束,并且路径中的每条边仅使用一次。

+ +

 

+ +

示例 1:

+ +
输入:n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]
+输出:3
+解释:长度最小的循环是:0 -> 1 -> 2 -> 0 
+
+ +

示例 2:

+ +
输入:n = 4, edges = [[0,1],[0,2]]
+输出:-1
+解释:图中不存在循环
+
+ +

 

+ +

提示:

+ +
    +
  • 2 <= n <= 1000
  • +
  • 1 <= edges.length <= 1000
  • +
  • edges[i].length == 2
  • +
  • 0 <= ui, vi < n
  • +
  • ui != vi
  • +
  • 不存在重复的边
  • +
+ +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: + def bfs(u: int) -> int: + dist = [-1] * n + dist[u] = 0 + q = deque([(u, -1)]) + while q: + u, fa = q.popleft() + for v in g[u]: + if dist[v] < 0: + dist[v] = dist[u] + 1 + q.append((v, u)) + elif v != fa: + return dist[u] + dist[v] + 1 + return inf + + g = defaultdict(list) + for u, v in edges: + g[u].append(v) + g[v].append(u) + ans = min(bfs(i) for i in range(n)) + return ans if ans < inf else -1 +``` + +### **Java** + + + +```java +class Solution { + private List[] g; + private final int inf = 1 << 30; + + public int findShortestCycle(int n, int[][] edges) { + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : edges) { + int u = e[0], v = e[1]; + g[u].add(v); + g[v].add(u); + } + int ans = inf; + for (int i = 0; i < n; ++i) { + ans = Math.min(ans, bfs(i)); + } + return ans < inf ? ans : -1; + } + + private int bfs(int u) { + int[] dist = new int[g.length]; + Arrays.fill(dist, -1); + dist[u] = 0; + Deque q = new ArrayDeque<>(); + q.offer(new int[] {u, -1}); + while (!q.isEmpty()) { + var p = q.poll(); + u = p[0]; + int fa = p[1]; + for (int v : g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.offer(new int[] {v, u}); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findShortestCycle(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0], v = e[1]; + g[u].push_back(v); + g[v].push_back(u); + } + const int inf = 1 << 30; + auto bfs = [&](int u) -> int { + int dist[n]; + memset(dist, -1, sizeof(dist)); + dist[u] = 0; + queue> q; + q.emplace(u, -1); + while (!q.empty()) { + auto p = q.front(); + u = p.first; + int fa = p.second; + q.pop(); + for (int v : g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.emplace(v, u); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + }; + int ans = inf; + for (int i = 0; i < n; ++i) { + ans = min(ans, bfs(i)); + } + return ans < inf ? ans : -1; + } +}; +``` + +### **Go** + +```go +func findShortestCycle(n int, edges [][]int) int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0], e[1] + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + const inf = 1 << 30 + bfs := func(u int) int { + dist := make([]int, n) + for i := range dist { + dist[i] = -1 + } + dist[u] = 0 + q := [][2]int{{u, -1}} + for len(q) > 0 { + p := q[0] + u = p[0] + fa := p[1] + q = q[1:] + for _, v := range g[u] { + if dist[v] < 0 { + dist[v] = dist[u] + 1 + q = append(q, [2]int{v, u}) + } else if v != fa { + return dist[u] + dist[v] + 1 + } + } + } + return inf + } + ans := inf + for i := 0; i < n; i++ { + ans = min(ans, bfs(i)) + } + if ans < inf { + return ans + } + return -1 +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **TypeScript** + +```ts +function findShortestCycle(n: number, edges: number[][]): number { + const g: number[][] = new Array(n).fill(0).map(() => []); + for (const [u, v] of edges) { + g[u].push(v); + g[v].push(u); + } + const inf = 1 << 30; + let ans = inf; + const bfs = (u: number) => { + const dist: number[] = new Array(n).fill(-1); + dist[u] = 0; + const q: number[][] = [[u, -1]]; + while (q.length) { + const p = q.shift()!; + u = p[0]; + const fa = p[1]; + for (const v of g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.push([v, u]); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + }; + for (let i = 0; i < n; ++i) { + ans = Math.min(ans, bfs(i)); + } + return ans < inf ? ans : -1; +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/README_EN.md b/solution/2600-2699/2608.Shortest Cycle in a Graph/README_EN.md new file mode 100644 index 0000000000000..5da0c27cc593c --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/README_EN.md @@ -0,0 +1,258 @@ +# [2608. Shortest Cycle in a Graph](https://leetcode.com/problems/shortest-cycle-in-a-graph) + +[中文文档](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README.md) + +## Description + +

There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

+ +

Return the length of the shortest cycle in the graph. If no cycle exists, return -1.

+ +

A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.

+ +

 

+

Example 1:

+ +
+Input: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]
+Output: 3
+Explanation: The cycle with the smallest length is : 0 -> 1 -> 2 -> 0 
+
+ +

Example 2:

+ +
+Input: n = 4, edges = [[0,1],[0,2]]
+Output: -1
+Explanation: There are no cycles in this graph.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 1000
  • +
  • 1 <= edges.length <= 1000
  • +
  • edges[i].length == 2
  • +
  • 0 <= ui, vi < n
  • +
  • ui != vi
  • +
  • There are no repeated edges.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: + def bfs(u: int) -> int: + dist = [-1] * n + dist[u] = 0 + q = deque([(u, -1)]) + while q: + u, fa = q.popleft() + for v in g[u]: + if dist[v] < 0: + dist[v] = dist[u] + 1 + q.append((v, u)) + elif v != fa: + return dist[u] + dist[v] + 1 + return inf + + g = defaultdict(list) + for u, v in edges: + g[u].append(v) + g[v].append(u) + ans = min(bfs(i) for i in range(n)) + return ans if ans < inf else -1 +``` + +### **Java** + +```java +class Solution { + private List[] g; + private final int inf = 1 << 30; + + public int findShortestCycle(int n, int[][] edges) { + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : edges) { + int u = e[0], v = e[1]; + g[u].add(v); + g[v].add(u); + } + int ans = inf; + for (int i = 0; i < n; ++i) { + ans = Math.min(ans, bfs(i)); + } + return ans < inf ? ans : -1; + } + + private int bfs(int u) { + int[] dist = new int[g.length]; + Arrays.fill(dist, -1); + dist[u] = 0; + Deque q = new ArrayDeque<>(); + q.offer(new int[] {u, -1}); + while (!q.isEmpty()) { + var p = q.poll(); + u = p[0]; + int fa = p[1]; + for (int v : g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.offer(new int[] {v, u}); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findShortestCycle(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0], v = e[1]; + g[u].push_back(v); + g[v].push_back(u); + } + const int inf = 1 << 30; + auto bfs = [&](int u) -> int { + int dist[n]; + memset(dist, -1, sizeof(dist)); + dist[u] = 0; + queue> q; + q.emplace(u, -1); + while (!q.empty()) { + auto p = q.front(); + u = p.first; + int fa = p.second; + q.pop(); + for (int v : g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.emplace(v, u); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + }; + int ans = inf; + for (int i = 0; i < n; ++i) { + ans = min(ans, bfs(i)); + } + return ans < inf ? ans : -1; + } +}; +``` + +### **Go** + +```go +func findShortestCycle(n int, edges [][]int) int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0], e[1] + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + const inf = 1 << 30 + bfs := func(u int) int { + dist := make([]int, n) + for i := range dist { + dist[i] = -1 + } + dist[u] = 0 + q := [][2]int{{u, -1}} + for len(q) > 0 { + p := q[0] + u = p[0] + fa := p[1] + q = q[1:] + for _, v := range g[u] { + if dist[v] < 0 { + dist[v] = dist[u] + 1 + q = append(q, [2]int{v, u}) + } else if v != fa { + return dist[u] + dist[v] + 1 + } + } + } + return inf + } + ans := inf + for i := 0; i < n; i++ { + ans = min(ans, bfs(i)) + } + if ans < inf { + return ans + } + return -1 +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **TypeScript** + +```ts +function findShortestCycle(n: number, edges: number[][]): number { + const g: number[][] = new Array(n).fill(0).map(() => []); + for (const [u, v] of edges) { + g[u].push(v); + g[v].push(u); + } + const inf = 1 << 30; + let ans = inf; + const bfs = (u: number) => { + const dist: number[] = new Array(n).fill(-1); + dist[u] = 0; + const q: number[][] = [[u, -1]]; + while (q.length) { + const p = q.shift()!; + u = p[0]; + const fa = p[1]; + for (const v of g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.push([v, u]); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + }; + for (let i = 0; i < n; ++i) { + ans = Math.min(ans, bfs(i)); + } + return ans < inf ? ans : -1; +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.cpp b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.cpp new file mode 100644 index 0000000000000..661148e7ab15f --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int findShortestCycle(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0], v = e[1]; + g[u].push_back(v); + g[v].push_back(u); + } + const int inf = 1 << 30; + auto bfs = [&](int u) -> int { + int dist[n]; + memset(dist, -1, sizeof(dist)); + dist[u] = 0; + queue> q; + q.emplace(u, -1); + while (!q.empty()) { + auto p = q.front(); + u = p.first; + int fa = p.second; + q.pop(); + for (int v : g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.emplace(v, u); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + }; + int ans = inf; + for (int i = 0; i < n; ++i) { + ans = min(ans, bfs(i)); + } + return ans < inf ? ans : -1; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.go b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.go new file mode 100644 index 0000000000000..62006bdb56608 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.go @@ -0,0 +1,47 @@ +func findShortestCycle(n int, edges [][]int) int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0], e[1] + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + const inf = 1 << 30 + bfs := func(u int) int { + dist := make([]int, n) + for i := range dist { + dist[i] = -1 + } + dist[u] = 0 + q := [][2]int{{u, -1}} + for len(q) > 0 { + p := q[0] + u = p[0] + fa := p[1] + q = q[1:] + for _, v := range g[u] { + if dist[v] < 0 { + dist[v] = dist[u] + 1 + q = append(q, [2]int{v, u}) + } else if v != fa { + return dist[u] + dist[v] + 1 + } + } + } + return inf + } + ans := inf + for i := 0; i < n; i++ { + ans = min(ans, bfs(i)) + } + if ans < inf { + return ans + } + return -1 +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} \ No newline at end of file diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.java b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.java new file mode 100644 index 0000000000000..e8a2bf22ffd84 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.java @@ -0,0 +1,41 @@ +class Solution { + private List[] g; + private final int inf = 1 << 30; + + public int findShortestCycle(int n, int[][] edges) { + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : edges) { + int u = e[0], v = e[1]; + g[u].add(v); + g[v].add(u); + } + int ans = inf; + for (int i = 0; i < n; ++i) { + ans = Math.min(ans, bfs(i)); + } + return ans < inf ? ans : -1; + } + + private int bfs(int u) { + int[] dist = new int[g.length]; + Arrays.fill(dist, -1); + dist[u] = 0; + Deque q = new ArrayDeque<>(); + q.offer(new int[] {u, -1}); + while (!q.isEmpty()) { + var p = q.poll(); + u = p[0]; + int fa = p[1]; + for (int v : g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.offer(new int[] {v, u}); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py new file mode 100644 index 0000000000000..8166ca14c4657 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.py @@ -0,0 +1,22 @@ +class Solution: + def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: + def bfs(u: int) -> int: + dist = [-1] * n + dist[u] = 0 + q = deque([(u, -1)]) + while q: + u, fa = q.popleft() + for v in g[u]: + if dist[v] < 0: + dist[v] = dist[u] + 1 + q.append((v, u)) + elif v != fa: + return dist[u] + dist[v] + 1 + return inf + + g = defaultdict(list) + for u, v in edges: + g[u].append(v) + g[v].append(u) + ans = min(bfs(i) for i in range(n)) + return ans if ans < inf else -1 diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.ts b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.ts new file mode 100644 index 0000000000000..71a545998d326 --- /dev/null +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/Solution.ts @@ -0,0 +1,32 @@ +function findShortestCycle(n: number, edges: number[][]): number { + const g: number[][] = new Array(n).fill(0).map(() => []); + for (const [u, v] of edges) { + g[u].push(v); + g[v].push(u); + } + const inf = 1 << 30; + let ans = inf; + const bfs = (u: number) => { + const dist: number[] = new Array(n).fill(-1); + dist[u] = 0; + const q: number[][] = [[u, -1]]; + while (q.length) { + const p = q.shift()!; + u = p[0]; + const fa = p[1]; + for (const v of g[u]) { + if (dist[v] < 0) { + dist[v] = dist[u] + 1; + q.push([v, u]); + } else if (v != fa) { + return dist[u] + dist[v] + 1; + } + } + } + return inf; + }; + for (let i = 0; i < n; ++i) { + ans = Math.min(ans, bfs(i)); + } + return ans < inf ? ans : -1; +} diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/images/cropped.png b/solution/2600-2699/2608.Shortest Cycle in a Graph/images/cropped.png new file mode 100644 index 0000000000000000000000000000000000000000..a9dc048c9842d3a73b6b6ecc4331e75d3591e0fe GIT binary patch literal 16687 zcmb_^cR1F4{I5N3%9c%%jBq1lubYsvS7b{`X0rFrCM#u=nNdde$QBYJv+NPFxAVTA z-*wLU|6J#~p004~J3iz6eyz_FuKw`e6$Bju0|VoVvJy%Y0|PS<{@f?PgP+`)o$G_Y zFr78;$zgmPU|5B3aI9q?$YNkr#1NgC;llTX4oU{j7#LUE(SI!=)aVA zvNC)5%-)Vg``HUC3<0Eopcs;040(q|KtN0YDJCQ`(%$|E14AZR86~UjX8d;=-;Hwg zC*Jmbt=E2Ag-)mnI`HyDf*9?UIB%=&eL?E1b;=g`h|tj5Ql|@ zp}(;GKVPB0=nnaR`S6YT#QmMHdofIfeJOguWzxinwTS5YQDH`rN5Q*tbSB!8UCoo?tPu_Ws?*|{c^hJL!Ht` zI-|vUYC46Q3N_?$HT*QOeRfl|Ss_>G^E;y%i|wZC@(dHX)HD62&U3ECin-V%BF*Gn z4mTgWEcQ~lY>e|)J^#t;vN4iA;w#XC!}C6kn%q1Mv`h5 zsLKl3j3|v3XvpW?Pk#98kJDTWX4T78O(EwcRhK_s37>ImWCzg+ScY+Fn)n>&F;K)UBWYr_ zq8UV4DVjd0W$50#pQJ7Lq+fla(&~rxwDtFFg`#Ia@&!1j%gyA4>}MprL&7BdTm2Y9 z!p(`X8717*gF{1$%bG79-Bfv_l;P6M>~kc$#Drx2-sJ6>n!&<4IF~Qzq+hIC%0|k< za@(-FKgS(YD$23Ev)8`3*^fO3NLW6mB`L1nJ8&E#Ho2cno%DCH(7_^XYf(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xGN!xJ^7(Z%&9tKF;q} z3!1?ZE(7+ZhBkg)QKZFEFw^%9{a|55=wQ+kt15{|K(0Jh-r>~;Ctz_pfb=byG2yw1 zR!m8$UdPRSWOltot6Ic4<9Cwa^m@-DkYApp(z`(h!-@p^S6JAJi7W;BTz;LO{sR;W zmEK`0gM!mmC={H6MxliN&sXR#EZhHoet2E2@Dlrt(c?*`r&RDiHo(A8R(Oc|C}$e* FzW@QVMnC`n literal 0 HcmV?d00001 diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/images/croppedagin.png b/solution/2600-2699/2608.Shortest Cycle in a Graph/images/croppedagin.png new file mode 100644 index 0000000000000000000000000000000000000000..a84acb7bbc948ac9bd9a98e99e65a21fc9fab5d0 GIT binary patch literal 9317 zcmeI2=R2HT*zQM<=qYOS=zS)LE_xSj5Iq9(ZgU6i4xI8 zi1B!}tar_KSLsHgv1Rmb;W6U_(*PR#p~4HCek$~7ri3bdsACiLrs}B^d^r0KVb}EvRPs* zO-C3pk2UmK1dmoS<@u0rSuRPiGGc3r+NbrQa3jN>9{{JpWbQ$D} zp<1Mj?^bqWzFwWs0Dg zV4AQc)MtA^-T!PN#Za;M!KX)WZ3F)BOfT4hccr+0ar(FPUN~uS3ZG#g28O^D=xxl;&tGKBmhsZq{8g)a4qn*xcxTCVYpS6ga=2QMP?D?gqJ&rf4HknU z2W4{R2rh%8q0Wgfu>}umUB}GrP=yIIP0DbWI99naLF0E?|7zF9E8SUTJk^vs?eLH7 zbau4e-nRSGF~Jh%GB~2S!0S=$TBx0(VJoehETEBbnA+fvw7Yr!HylB-2zY<|j0DQB(+8xw2p!KYap z!AJ8^B{ogZtJyKK&o_!9Y1k|B3ksZzH0P4x?Azkxj~7{1hA?%!dYSf;kG{19tiFv3 zYt8cwSRBI4x=wyBueEO{Jiofgr!O`$bD<@i04v$FH3QagpW*ad@v51?V1b+SaAQsP~XJ@Krrb8Vp|;QlACG_|$3 z4c8}XT*QBL5Y;U_JA6D|VRORdOJA>6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dHv>pGiu3$_4CWe?ngKYdfKn@ zc&SL}9smzw3ILU}ip*BNL5^%1h5C!omv=CJD>=T48CB{r^o?I_EYhi0e!SDZJ`Lut zCDVZlkKY})G2DOJ&D;nsu>^*jvW0Do{cgZs5s>p;Gx5&G^rLG$`fohw4q80Oqj=!wLn~<;x&jgLem{ z1rrNpzPG>ND?*I|kw6p7)n;AWyL_9-yLBg?MS3fJfzTrKmPvk9H<6C++f#xFW*Tss zVX}&Bc@ZDIf((N&Tj=WVu5& zB6hmdFE)w?VxYn70kk!uVg_Bbs1D}U{YqPf2J#RYfBuPuPoYF)I&cfX zo(;qgWo{UE{RZsC7%KN{p)2_lTOG*nifjLWSx74a+ofmwUj+F*CbuoGQY&E zl=l>`>UK}KJTdO112dGJoEulkD_c%VtOH~T?(G$3*e0KYWCcs4^M54{8pYbL^;c&{U`ky$Re-yZoWy`=JOk&FbutgL2-2@u!S#IEt zHn~%MS67Z6*ABfM8SH2=#W2kGIylzhId@4a6N&sP;&FJR;LEe$1fe3pq@3{6`ICym z^h55&9<9$M0ms9%3gUx0>W+7)@K9fdnB70g7kjI36KIndjvI$IhQ##SmbU*LHPvY0WYUdebHaGqU24k;Btj((dUp0od;QTe2W#|3AY8y~03p@Cu8$rUyPo pQga;ih?I`*fAoh*LX0oT%vc4Qq^5j)!KZ*A+Uf>s6)N^&{|EGA+!O!+ literal 0 HcmV?d00001 diff --git a/solution/CONTEST_README.md b/solution/CONTEST_README.md index 83727101bfa1c..1b204d626fcb3 100644 --- a/solution/CONTEST_README.md +++ b/solution/CONTEST_README.md @@ -24,6 +24,14 @@ ## 往期竞赛 +#### 第 101 场双周赛(2023-04-01 22:30, 90 分钟) 参赛人数 3353 + +- [2605. 从两个数字数组里生成最小数字](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README.md) +- [2606. 找到最大开销的子字符串](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README.md) +- [2607. 使子数组元素和相等](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README.md) +- [2608. 图中的最短环](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README.md) + + #### 第 338 场周赛(2023-03-26 10:30, 90 分钟) 参赛人数 5594 - [2600. K 件物品的最大和](/solution/2600-2699/2600.K%20Items%20With%20the%20Maximum%20Sum/README.md) @@ -1531,7 +1539,7 @@ #### 第 38 场双周赛(2020-10-31 22:30, 90 分钟) 参赛人数 2004 - [1636. 按照频率将数组升序排序](/solution/1600-1699/1636.Sort%20Array%20by%20Increasing%20Frequency/README.md) -- [1637. 两点之间不包含任何点的最宽垂直面积](/solution/1600-1699/1637.Widest%20Vertical%20Area%20Between%20Two%20Points%20Containing%20No%20Points/README.md) +- [1637. 两点之间不包含任何点的最宽垂直区域](/solution/1600-1699/1637.Widest%20Vertical%20Area%20Between%20Two%20Points%20Containing%20No%20Points/README.md) - [1638. 统计只差一个字符的子串数目](/solution/1600-1699/1638.Count%20Substrings%20That%20Differ%20by%20One%20Character/README.md) - [1639. 通过给定词典构造目标字符串的方案数](/solution/1600-1699/1639.Number%20of%20Ways%20to%20Form%20a%20Target%20String%20Given%20a%20Dictionary/README.md) diff --git a/solution/CONTEST_README_EN.md b/solution/CONTEST_README_EN.md index 8f8e6f3f8fd13..6ed87c1f97f8e 100644 --- a/solution/CONTEST_README_EN.md +++ b/solution/CONTEST_README_EN.md @@ -25,6 +25,14 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## Past Contests +#### Biweekly Contest 101 + +- [2605. Form Smallest Number From Two Digit Arrays](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README_EN.md) +- [2606. Find the Substring With Maximum Cost](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README_EN.md) +- [2607. Make K-Subarray Sums Equal](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README_EN.md) +- [2608. Shortest Cycle in a Graph](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README_EN.md) + + #### Weekly Contest 338 - [2600. K Items With the Maximum Sum](/solution/2600-2699/2600.K%20Items%20With%20the%20Maximum%20Sum/README_EN.md) diff --git a/solution/README.md b/solution/README.md index f6ec139af16d3..a7ca4ed6aa99b 100644 --- a/solution/README.md +++ b/solution/README.md @@ -2615,6 +2615,10 @@ | 2602 | [使数组元素全部相等的最少操作次数](/solution/2600-2699/2602.Minimum%20Operations%20to%20Make%20All%20Array%20Elements%20Equal/README.md) | `数组`,`二分查找`,`前缀和`,`排序` | 中等 | 第 338 场周赛 | | 2603 | [收集树中金币](/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/README.md) | `树`,`图`,`拓扑排序`,`数组` | 困难 | 第 338 场周赛 | | 2604 | [Minimum Time to Eat All Grains](/solution/2600-2699/2604.Minimum%20Time%20to%20Eat%20All%20Grains/README.md) | | 困难 | 🔒 | +| 2605 | [从两个数字数组里生成最小数字](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README.md) | | 简单 | 第 101 场双周赛 | +| 2606 | [找到最大开销的子字符串](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README.md) | | 中等 | 第 101 场双周赛 | +| 2607 | [使子数组元素和相等](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README.md) | | 中等 | 第 101 场双周赛 | +| 2608 | [图中的最短环](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README.md) | | 困难 | 第 101 场双周赛 | ## 版权 diff --git a/solution/README_EN.md b/solution/README_EN.md index 7c1c5d84810e1..53f28a66c9b33 100644 --- a/solution/README_EN.md +++ b/solution/README_EN.md @@ -2613,6 +2613,10 @@ Press Control+F(or Command+F on the | 2602 | [Minimum Operations to Make All Array Elements Equal](/solution/2600-2699/2602.Minimum%20Operations%20to%20Make%20All%20Array%20Elements%20Equal/README_EN.md) | `Array`,`Binary Search`,`Prefix Sum`,`Sorting` | Medium | Weekly Contest 338 | | 2603 | [Collect Coins in a Tree](/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/README_EN.md) | `Tree`,`Graph`,`Topological Sort`,`Array` | Hard | Weekly Contest 338 | | 2604 | [Minimum Time to Eat All Grains](/solution/2600-2699/2604.Minimum%20Time%20to%20Eat%20All%20Grains/README_EN.md) | | Hard | 🔒 | +| 2605 | [Form Smallest Number From Two Digit Arrays](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README_EN.md) | | Easy | Biweekly Contest 101 | +| 2606 | [Find the Substring With Maximum Cost](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README_EN.md) | | Medium | Biweekly Contest 101 | +| 2607 | [Make K-Subarray Sums Equal](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README_EN.md) | | Medium | Biweekly Contest 101 | +| 2608 | [Shortest Cycle in a Graph](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README_EN.md) | | Hard | Biweekly Contest 101 | ## Copyright diff --git a/solution/summary.md b/solution/summary.md index f88aa8dfdbfab..5c6050fad9990 100644 --- a/solution/summary.md +++ b/solution/summary.md @@ -2656,3 +2656,7 @@ - [2602.使数组元素全部相等的最少操作次数](/solution/2600-2699/2602.Minimum%20Operations%20to%20Make%20All%20Array%20Elements%20Equal/README.md) - [2603.收集树中金币](/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/README.md) - [2604.Minimum Time to Eat All Grains](/solution/2600-2699/2604.Minimum%20Time%20to%20Eat%20All%20Grains/README.md) + - [2605.从两个数字数组里生成最小数字](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README.md) + - [2606.找到最大开销的子字符串](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README.md) + - [2607.使子数组元素和相等](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README.md) + - [2608.图中的最短环](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README.md) diff --git a/solution/summary_en.md b/solution/summary_en.md index 799fe2eb87aa6..847f56dcb01c3 100644 --- a/solution/summary_en.md +++ b/solution/summary_en.md @@ -2656,3 +2656,7 @@ - [2602.Minimum Operations to Make All Array Elements Equal](/solution/2600-2699/2602.Minimum%20Operations%20to%20Make%20All%20Array%20Elements%20Equal/README_EN.md) - [2603.Collect Coins in a Tree](/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/README_EN.md) - [2604.Minimum Time to Eat All Grains](/solution/2600-2699/2604.Minimum%20Time%20to%20Eat%20All%20Grains/README_EN.md) + - [2605.Form Smallest Number From Two Digit Arrays](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README_EN.md) + - [2606.Find the Substring With Maximum Cost](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README_EN.md) + - [2607.Make K-Subarray Sums Equal](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README_EN.md) + - [2608.Shortest Cycle in a Graph](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README_EN.md) From 523a4f68531485fede979be6501d856a691b2284 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Sun, 2 Apr 2023 13:20:40 +0800 Subject: [PATCH 2/3] feat: add solutions to lc problems: No.2609~2612 * No.2609.Find the Longest Balanced Substring of a Binary String * No.2610.Convert an Array Into a 2D Array With Conditions * No.2611.Mice and Cheese * No.2612.Minimum Reverse Operations --- .../README.md | 10 +- .../README.md | 187 ++++++++++++++++++ .../README_EN.md | 177 +++++++++++++++++ .../Solution.cpp | 26 +++ .../Solution.go | 29 +++ .../Solution.java | 26 +++ .../Solution.py | 18 ++ .../README.md | 153 ++++++++++++++ .../README_EN.md | 145 ++++++++++++++ .../Solution.cpp | 21 ++ .../Solution.go | 16 ++ .../Solution.java | 20 ++ .../Solution.py | 10 + .../2600-2699/2611.Mice and Cheese/README.md | 149 ++++++++++++++ .../2611.Mice and Cheese/README_EN.md | 139 +++++++++++++ .../2611.Mice and Cheese/Solution.cpp | 17 ++ .../2611.Mice and Cheese/Solution.go | 18 ++ .../2611.Mice and Cheese/Solution.java | 18 ++ .../2611.Mice and Cheese/Solution.py | 6 + .../2612.Minimum Reverse Operations/README.md | 157 +++++++++++++++ .../README_EN.md | 143 ++++++++++++++ .../Solution.java | 28 +++ .../Solution.py | 24 +++ solution/CONTEST_README.md | 8 + solution/CONTEST_README_EN.md | 8 + solution/README.md | 4 + solution/README_EN.md | 4 + solution/summary.md | 4 + solution/summary_en.md | 4 + 29 files changed, 1565 insertions(+), 4 deletions(-) create mode 100644 solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README.md create mode 100644 solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README_EN.md create mode 100644 solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.cpp create mode 100644 solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.go create mode 100644 solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.java create mode 100644 solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.py create mode 100644 solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README.md create mode 100644 solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README_EN.md create mode 100644 solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.cpp create mode 100644 solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.go create mode 100644 solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.java create mode 100644 solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.py create mode 100644 solution/2600-2699/2611.Mice and Cheese/README.md create mode 100644 solution/2600-2699/2611.Mice and Cheese/README_EN.md create mode 100644 solution/2600-2699/2611.Mice and Cheese/Solution.cpp create mode 100644 solution/2600-2699/2611.Mice and Cheese/Solution.go create mode 100644 solution/2600-2699/2611.Mice and Cheese/Solution.java create mode 100644 solution/2600-2699/2611.Mice and Cheese/Solution.py create mode 100644 solution/2600-2699/2612.Minimum Reverse Operations/README.md create mode 100644 solution/2600-2699/2612.Minimum Reverse Operations/README_EN.md create mode 100644 solution/2600-2699/2612.Minimum Reverse Operations/Solution.java create mode 100644 solution/2600-2699/2612.Minimum Reverse Operations/Solution.py diff --git a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md index 1ac2a1a5cd6fa..52e81045616a8 100644 --- a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md +++ b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md @@ -8,7 +8,7 @@

现在有一个正凸多边形,其上共有 n 个顶点。顶点按顺时针方向从 0n - 1 依次编号。每个顶点上 正好有一只猴子 。下图中是一个 6 个顶点的凸多边形。

-

+

每个猴子同时移动到相邻的顶点。顶点 i 的相邻顶点可以是:

@@ -17,7 +17,7 @@
  • 逆时针方向的顶点 (i - 1 + n) % n
  • -

    如果移动后至少有两个猴子位于同一顶点,则会发生 碰撞

    +

    如果移动后至少有两只猴子停留在同一个顶点上或者相交在一条边上,则会发生 碰撞

    返回猴子至少发生 一次碰撞 的移动方法数。由于答案可能非常大,请返回对 109+7 取余后的结果。

    @@ -27,7 +27,8 @@

    示例 1:

    -
    输入:n = 3
    +
    +输入:n = 3
     输出:6
     解释:共计 8 种移动方式。
     下面列出两种会发生碰撞的方式:
    @@ -38,7 +39,8 @@
     
     

    示例 2:

    -
    输入:n = 4
    +
    +输入:n = 4
     输出:14
     解释:可以证明,有 14 种让猴子碰撞的方法。
    diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README.md b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README.md new file mode 100644 index 0000000000000..e19b6517b10a2 --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README.md @@ -0,0 +1,187 @@ +# [2609. 最长平衡子字符串](https://leetcode.cn/problems/find-the-longest-balanced-substring-of-a-binary-string) + +[English Version](/solution/2600-2699/2609.Find%20the%20Longest%20Balanced%20Substring%20of%20a%20Binary%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个仅由 01 组成的二进制字符串 s  

    + +

    如果子字符串中 所有的 0 都在 1 之前 且其中 0 的数量等于 1 的数量,则认为 s 的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。 

    + +

    返回  s 中最长的平衡子字符串长度。

    + +

    子字符串是字符串中的一个连续字符序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "01000111"
    +输出:6
    +解释:最长的平衡子字符串是 "000111" ,长度为 6 。
    +
    + +

    示例 2:

    + +
    +输入:s = "00111"
    +输出:4
    +解释:最长的平衡子字符串是 "0011" ,长度为  4 。
    +
    + +

    示例 3:

    + +
    +输入:s = "111"
    +输出:0
    +解释:除了空子字符串之外不存在其他平衡子字符串,所以答案为 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 50
    • +
    • '0' <= s[i] <= '1'
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def findTheLongestBalancedSubstring(self, s: str) -> int: + def check(i, j): + cnt = 0 + for k in range(i, j + 1): + if s[k] == '1': + cnt += 1 + elif cnt: + return False + return cnt * 2 == (j - i + 1) + + n = len(s) + ans = 0 + for i in range(n): + for j in range(i + 1, n): + if check(i, j): + ans = max(ans, j - i + 1) + return ans +``` + +### **Java** + + + +```java +class Solution { + public int findTheLongestBalancedSubstring(String s) { + int n = s.length(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (check(s, i, j)) { + ans = Math.max(ans, j - i + 1); + } + } + } + return ans; + } + + private boolean check(String s, int i, int j) { + int cnt = 0; + for (int k = i; k <= j; ++k) { + if (s.charAt(k) == '1') { + ++cnt; + } else if (cnt > 0) { + return false; + } + } + return cnt * 2 == j - i + 1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findTheLongestBalancedSubstring(string s) { + int n = s.size(); + int ans = 0; + auto check = [&](int i, int j) -> bool { + int cnt = 0; + for (int k = i; k <= j; ++k) { + if (s[k] == '1') { + ++cnt; + } else if (cnt) { + return false; + } + } + return cnt * 2 == j - i + 1; + }; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (check(i, j)) { + ans = max(ans, j - i + 1); + } + } + } + return ans; + } +}; +``` + +### **Go** + +```go +func findTheLongestBalancedSubstring(s string) (ans int) { + n := len(s) + check := func(i, j int) bool { + cnt := 0 + for k := i; k <= j; k++ { + if s[k] == '1' { + cnt++ + } else if cnt > 0 { + return false + } + } + return cnt*2 == j-i+1 + } + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if check(i, j) { + ans = max(ans, j-i+1) + } + } + } + return +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README_EN.md b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README_EN.md new file mode 100644 index 0000000000000..503e3023c62e4 --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README_EN.md @@ -0,0 +1,177 @@ +# [2609. Find the Longest Balanced Substring of a Binary String](https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string) + +[中文文档](/solution/2600-2699/2609.Find%20the%20Longest%20Balanced%20Substring%20of%20a%20Binary%20String/README.md) + +## Description + +

    You are given a binary string s consisting only of zeroes and ones.

    + +

    A substring of s is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.

    + +

    Return the length of the longest balanced substring of s.

    + +

    A substring is a contiguous sequence of characters within a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "01000111"
    +Output: 6
    +Explanation: The longest balanced substring is "000111", which has length 6.
    +
    + +

    Example 2:

    + +
    +Input: s = "00111"
    +Output: 4
    +Explanation: The longest balanced substring is "0011", which has length 4. 
    +
    + +

    Example 3:

    + +
    +Input: s = "111"
    +Output: 0
    +Explanation: There is no balanced substring except the empty substring, so the answer is 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 50
    • +
    • '0' <= s[i] <= '1'
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findTheLongestBalancedSubstring(self, s: str) -> int: + def check(i, j): + cnt = 0 + for k in range(i, j + 1): + if s[k] == '1': + cnt += 1 + elif cnt: + return False + return cnt * 2 == (j - i + 1) + + n = len(s) + ans = 0 + for i in range(n): + for j in range(i + 1, n): + if check(i, j): + ans = max(ans, j - i + 1) + return ans +``` + +### **Java** + +```java +class Solution { + public int findTheLongestBalancedSubstring(String s) { + int n = s.length(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (check(s, i, j)) { + ans = Math.max(ans, j - i + 1); + } + } + } + return ans; + } + + private boolean check(String s, int i, int j) { + int cnt = 0; + for (int k = i; k <= j; ++k) { + if (s.charAt(k) == '1') { + ++cnt; + } else if (cnt > 0) { + return false; + } + } + return cnt * 2 == j - i + 1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findTheLongestBalancedSubstring(string s) { + int n = s.size(); + int ans = 0; + auto check = [&](int i, int j) -> bool { + int cnt = 0; + for (int k = i; k <= j; ++k) { + if (s[k] == '1') { + ++cnt; + } else if (cnt) { + return false; + } + } + return cnt * 2 == j - i + 1; + }; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (check(i, j)) { + ans = max(ans, j - i + 1); + } + } + } + return ans; + } +}; +``` + +### **Go** + +```go +func findTheLongestBalancedSubstring(s string) (ans int) { + n := len(s) + check := func(i, j int) bool { + cnt := 0 + for k := i; k <= j; k++ { + if s[k] == '1' { + cnt++ + } else if cnt > 0 { + return false + } + } + return cnt*2 == j-i+1 + } + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if check(i, j) { + ans = max(ans, j-i+1) + } + } + } + return +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.cpp b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.cpp new file mode 100644 index 0000000000000..ba0182b36f851 --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int findTheLongestBalancedSubstring(string s) { + int n = s.size(); + int ans = 0; + auto check = [&](int i, int j) -> bool { + int cnt = 0; + for (int k = i; k <= j; ++k) { + if (s[k] == '1') { + ++cnt; + } else if (cnt) { + return false; + } + } + return cnt * 2 == j - i + 1; + }; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (check(i, j)) { + ans = max(ans, j - i + 1); + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.go b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.go new file mode 100644 index 0000000000000..d2d855c564c02 --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.go @@ -0,0 +1,29 @@ +func findTheLongestBalancedSubstring(s string) (ans int) { + n := len(s) + check := func(i, j int) bool { + cnt := 0 + for k := i; k <= j; k++ { + if s[k] == '1' { + cnt++ + } else if cnt > 0 { + return false + } + } + return cnt*2 == j-i+1 + } + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if check(i, j) { + ans = max(ans, j-i+1) + } + } + } + return +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} \ No newline at end of file diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.java b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.java new file mode 100644 index 0000000000000..163dbc7cd4096 --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.java @@ -0,0 +1,26 @@ +class Solution { + public int findTheLongestBalancedSubstring(String s) { + int n = s.length(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + if (check(s, i, j)) { + ans = Math.max(ans, j - i + 1); + } + } + } + return ans; + } + + private boolean check(String s, int i, int j) { + int cnt = 0; + for (int k = i; k <= j; ++k) { + if (s.charAt(k) == '1') { + ++cnt; + } else if (cnt > 0) { + return false; + } + } + return cnt * 2 == j - i + 1; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.py b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.py new file mode 100644 index 0000000000000..7b084c8db74ae --- /dev/null +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/Solution.py @@ -0,0 +1,18 @@ +class Solution: + def findTheLongestBalancedSubstring(self, s: str) -> int: + def check(i, j): + cnt = 0 + for k in range(i, j + 1): + if s[k] == '1': + cnt += 1 + elif cnt: + return False + return cnt * 2 == (j - i + 1) + + n = len(s) + ans = 0 + for i in range(n): + for j in range(i + 1, n): + if check(i, j): + ans = max(ans, j - i + 1) + return ans diff --git a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README.md b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README.md new file mode 100644 index 0000000000000..984fa53db681a --- /dev/null +++ b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README.md @@ -0,0 +1,153 @@ +# [2610. 转换二维数组](https://leetcode.cn/problems/convert-an-array-into-a-2d-array-with-conditions) + +[English Version](/solution/2600-2699/2610.Convert%20an%20Array%20Into%20a%202D%20Array%20With%20Conditions/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 。请你创建一个满足以下条件的二维数组:

    + +
      +
    • 二维数组应该 包含数组 nums 中的元素。
    • +
    • 二维数组中的每一行都包含 不同 的整数。
    • +
    • 二维数组的行数应尽可能
    • +
    + +

    返回结果数组。如果存在多种答案,则返回其中任何一种。

    + +

    请注意,二维数组的每一行上可以存在不同数量的元素。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,3,4,1,2,3,1]
    +输出:[[1,3,4,2],[1,3],[1]]
    +解释:根据题目要求可以创建包含以下几行元素的二维数组:
    +- 1,3,4,2
    +- 1,3
    +- 1
    +nums 中的所有元素都有用到,并且每一行都由不同的整数组成,所以这是一个符合题目要求的答案。
    +可以证明无法创建少于三行且符合题目要求的二维数组。
    + +

    示例 2:

    + +
    输入:nums = [1,2,3,4]
    +输出:[[4,3,2,1]]
    +解释:nums 中的所有元素都不同,所以我们可以将其全部保存在二维数组中的第一行。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 200
    • +
    • 1 <= nums[i] <= nums.length
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def findMatrix(self, nums: List[int]) -> List[List[int]]: + cnt = Counter(nums) + ans = [] + for x, v in cnt.items(): + for i in range(v): + if len(ans) <= i: + ans.append([]) + ans[i].append(x) + return ans +``` + +### **Java** + + + +```java +class Solution { + public List> findMatrix(int[] nums) { + List> ans = new ArrayList<>(); + int n = nums.length; + int[] cnt = new int[n + 1]; + for (int x : nums) { + ++cnt[x]; + } + for (int x = 1; x <= n; ++x) { + int v = cnt[x]; + for (int j = 0; j < v; ++j) { + if (ans.size() <= j) { + ans.add(new ArrayList<>()); + } + ans.get(j).add(x); + } + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> findMatrix(vector& nums) { + vector> ans; + int n = nums.size(); + vector cnt(n + 1); + for (int& x : nums) { + ++cnt[x]; + } + for (int x = 1; x <= n; ++x) { + int v = cnt[x]; + for (int j = 0; j < v; ++j) { + if (ans.size() <= j) { + ans.push_back({}); + } + ans[j].push_back(x); + } + } + return ans; + } +}; +``` + +### **Go** + +```go +func findMatrix(nums []int) (ans [][]int) { + n := len(nums) + cnt := make([]int, n+1) + for _, x := range nums { + cnt[x]++ + } + for x, v := range cnt { + for j := 0; j < v; j++ { + if len(ans) <= j { + ans = append(ans, []int{}) + } + ans[j] = append(ans[j], x) + } + } + return +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README_EN.md b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README_EN.md new file mode 100644 index 0000000000000..69aaf9075352e --- /dev/null +++ b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README_EN.md @@ -0,0 +1,145 @@ +# [2610. Convert an Array Into a 2D Array With Conditions](https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions) + +[中文文档](/solution/2600-2699/2610.Convert%20an%20Array%20Into%20a%202D%20Array%20With%20Conditions/README.md) + +## Description + +

    You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions:

    + +
      +
    • The 2D array should contain only the elements of the array nums.
    • +
    • Each row in the 2D array contains distinct integers.
    • +
    • The number of rows in the 2D array should be minimal.
    • +
    + +

    Return the resulting array. If there are multiple answers, return any of them.

    + +

    Note that the 2D array can have a different number of elements on each row.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,3,4,1,2,3,1]
    +Output: [[1,3,4,2],[1,3],[1]]
    +Explanation: We can create a 2D array that contains the following rows:
    +- 1,3,4,2
    +- 1,3
    +- 1
    +All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer.
    +It can be shown that we cannot have less than 3 rows in a valid array.
    + +

    Example 2:

    + +
    +Input: nums = [1,2,3,4]
    +Output: [[4,3,2,1]]
    +Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 200
    • +
    • 1 <= nums[i] <= nums.length
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findMatrix(self, nums: List[int]) -> List[List[int]]: + cnt = Counter(nums) + ans = [] + for x, v in cnt.items(): + for i in range(v): + if len(ans) <= i: + ans.append([]) + ans[i].append(x) + return ans +``` + +### **Java** + +```java +class Solution { + public List> findMatrix(int[] nums) { + List> ans = new ArrayList<>(); + int n = nums.length; + int[] cnt = new int[n + 1]; + for (int x : nums) { + ++cnt[x]; + } + for (int x = 1; x <= n; ++x) { + int v = cnt[x]; + for (int j = 0; j < v; ++j) { + if (ans.size() <= j) { + ans.add(new ArrayList<>()); + } + ans.get(j).add(x); + } + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> findMatrix(vector& nums) { + vector> ans; + int n = nums.size(); + vector cnt(n + 1); + for (int& x : nums) { + ++cnt[x]; + } + for (int x = 1; x <= n; ++x) { + int v = cnt[x]; + for (int j = 0; j < v; ++j) { + if (ans.size() <= j) { + ans.push_back({}); + } + ans[j].push_back(x); + } + } + return ans; + } +}; +``` + +### **Go** + +```go +func findMatrix(nums []int) (ans [][]int) { + n := len(nums) + cnt := make([]int, n+1) + for _, x := range nums { + cnt[x]++ + } + for x, v := range cnt { + for j := 0; j < v; j++ { + if len(ans) <= j { + ans = append(ans, []int{}) + } + ans[j] = append(ans[j], x) + } + } + return +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.cpp b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.cpp new file mode 100644 index 0000000000000..aa750945f269c --- /dev/null +++ b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector> findMatrix(vector& nums) { + vector> ans; + int n = nums.size(); + vector cnt(n + 1); + for (int& x : nums) { + ++cnt[x]; + } + for (int x = 1; x <= n; ++x) { + int v = cnt[x]; + for (int j = 0; j < v; ++j) { + if (ans.size() <= j) { + ans.push_back({}); + } + ans[j].push_back(x); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.go b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.go new file mode 100644 index 0000000000000..a435fc3291e8d --- /dev/null +++ b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.go @@ -0,0 +1,16 @@ +func findMatrix(nums []int) (ans [][]int) { + n := len(nums) + cnt := make([]int, n+1) + for _, x := range nums { + cnt[x]++ + } + for x, v := range cnt { + for j := 0; j < v; j++ { + if len(ans) <= j { + ans = append(ans, []int{}) + } + ans[j] = append(ans[j], x) + } + } + return +} \ No newline at end of file diff --git a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.java b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.java new file mode 100644 index 0000000000000..c6720c561c7bb --- /dev/null +++ b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.java @@ -0,0 +1,20 @@ +class Solution { + public List> findMatrix(int[] nums) { + List> ans = new ArrayList<>(); + int n = nums.length; + int[] cnt = new int[n + 1]; + for (int x : nums) { + ++cnt[x]; + } + for (int x = 1; x <= n; ++x) { + int v = cnt[x]; + for (int j = 0; j < v; ++j) { + if (ans.size() <= j) { + ans.add(new ArrayList<>()); + } + ans.get(j).add(x); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.py b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.py new file mode 100644 index 0000000000000..483c499efc9fe --- /dev/null +++ b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.py @@ -0,0 +1,10 @@ +class Solution: + def findMatrix(self, nums: List[int]) -> List[List[int]]: + cnt = Counter(nums) + ans = [] + for x, v in cnt.items(): + for i in range(v): + if len(ans) <= i: + ans.append([]) + ans[i].append(x) + return ans diff --git a/solution/2600-2699/2611.Mice and Cheese/README.md b/solution/2600-2699/2611.Mice and Cheese/README.md new file mode 100644 index 0000000000000..59d73328ffd41 --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/README.md @@ -0,0 +1,149 @@ +# [2611. 老鼠和奶酪](https://leetcode.cn/problems/mice-and-cheese) + +[English Version](/solution/2600-2699/2611.Mice%20and%20Cheese/README_EN.md) + +## 题目描述 + + + +

    有两只老鼠和 n 块不同类型的奶酪,每块奶酪都只能被其中一只老鼠吃掉。

    + +

    下标为 i 处的奶酪被吃掉的得分为:

    + +
      +
    • 如果第一只老鼠吃掉,则得分为 reward1[i] 。
    • +
    • 如果第二只老鼠吃掉,则得分为 reward2[i] 。
    • +
    + +

    给你一个正整数数组 reward1 ,一个正整数数组 reward2 ,和一个非负整数 k 。

    + +

    请你返回第一只老鼠恰好吃掉 k 块奶酪的情况下,最大 得分为多少。

    + +

     

    + +

    示例 1:

    + +
    +输入:reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2
    +输出:15
    +解释:这个例子中,第一只老鼠吃掉第 2 和 3 块奶酪(下标从 0 开始),第二只老鼠吃掉第 0 和 1 块奶酪。
    +总得分为 4 + 4 + 3 + 4 = 15 。
    +15 是最高得分。
    +
    + +

    示例 2:

    + +
    +输入:reward1 = [1,1], reward2 = [1,1], k = 2
    +输出:2
    +解释:这个例子中,第一只老鼠吃掉第 0 和 1 块奶酪(下标从 0 开始),第二只老鼠不吃任何奶酪。
    +总得分为 1 + 1 = 2 。
    +2 是最高得分。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n == reward1.length == reward2.length <= 105
    • +
    • 1 <= reward1[i], reward2[i] <= 1000
    • +
    • 0 <= k <= n
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: + n = len(reward1) + idx = sorted( + range(n), key=lambda i: reward1[i] - reward2[i], reverse=True) + return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:]) +``` + +### **Java** + + + +```java +class Solution { + public int miceAndCheese(int[] reward1, int[] reward2, int k) { + int n = reward1.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> reward1[j] - reward2[j] - (reward1[i] - reward2[i])); + int ans = 0; + for (int i = 0; i < k; ++i) { + ans += reward1[idx[i]]; + } + for (int i = k; i < n; ++i) { + ans += reward2[idx[i]]; + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int miceAndCheese(vector& reward1, vector& reward2, int k) { + int n = reward1.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return reward1[j] - reward2[j] < reward1[i] - reward2[i]; }); + int ans = 0; + for (int i = 0; i < k; ++i) { + ans += reward1[idx[i]]; + } + for (int i = k; i < n; ++i) { + ans += reward2[idx[i]]; + } + return ans; + } +}; +``` + +### **Go** + +```go +func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { + n := len(reward1) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { + i, j = idx[i], idx[j] + return reward1[j]-reward2[j] < reward1[i]-reward2[i] + }) + for i := 0; i < k; i++ { + ans += reward1[idx[i]] + } + for i := k; i < n; i++ { + ans += reward2[idx[i]] + } + return +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2611.Mice and Cheese/README_EN.md b/solution/2600-2699/2611.Mice and Cheese/README_EN.md new file mode 100644 index 0000000000000..b12a5168dd3b2 --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/README_EN.md @@ -0,0 +1,139 @@ +# [2611. Mice and Cheese](https://leetcode.com/problems/mice-and-cheese) + +[中文文档](/solution/2600-2699/2611.Mice%20and%20Cheese/README.md) + +## Description + +

    There are two mice and n different types of cheese, each type of cheese should be eaten by exactly one mouse.

    + +

    A point of the cheese with index i (0-indexed) is:

    + +
      +
    • reward1[i] if the first mouse eats it.
    • +
    • reward2[i] if the second mouse eats it.
    • +
    + +

    You are given a positive integer array reward1, a positive integer array reward2, and a non-negative integer k.

    + +

    Return the maximum points the mice can achieve if the first mouse eats exactly k types of cheese.

    + +

     

    +

    Example 1:

    + +
    +Input: reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2
    +Output: 15
    +Explanation: In this example, the first mouse eats the 2nd (0-indexed) and the 3rd types of cheese, and the second mouse eats the 0th and the 1st types of cheese.
    +The total points are 4 + 4 + 3 + 4 = 15.
    +It can be proven that 15 is the maximum total points that the mice can achieve.
    +
    + +

    Example 2:

    + +
    +Input: reward1 = [1,1], reward2 = [1,1], k = 2
    +Output: 2
    +Explanation: In this example, the first mouse eats the 0th (0-indexed) and 1st types of cheese, and the second mouse does not eat any cheese.
    +The total points are 1 + 1 = 2.
    +It can be proven that 2 is the maximum total points that the mice can achieve.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n == reward1.length == reward2.length <= 105
    • +
    • 1 <= reward1[i], reward2[i] <= 1000
    • +
    • 0 <= k <= n
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: + n = len(reward1) + idx = sorted( + range(n), key=lambda i: reward1[i] - reward2[i], reverse=True) + return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:]) +``` + +### **Java** + +```java +class Solution { + public int miceAndCheese(int[] reward1, int[] reward2, int k) { + int n = reward1.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> reward1[j] - reward2[j] - (reward1[i] - reward2[i])); + int ans = 0; + for (int i = 0; i < k; ++i) { + ans += reward1[idx[i]]; + } + for (int i = k; i < n; ++i) { + ans += reward2[idx[i]]; + } + return ans; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int miceAndCheese(vector& reward1, vector& reward2, int k) { + int n = reward1.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return reward1[j] - reward2[j] < reward1[i] - reward2[i]; }); + int ans = 0; + for (int i = 0; i < k; ++i) { + ans += reward1[idx[i]]; + } + for (int i = k; i < n; ++i) { + ans += reward2[idx[i]]; + } + return ans; + } +}; +``` + +### **Go** + +```go +func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { + n := len(reward1) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { + i, j = idx[i], idx[j] + return reward1[j]-reward2[j] < reward1[i]-reward2[i] + }) + for i := 0; i < k; i++ { + ans += reward1[idx[i]] + } + for i := k; i < n; i++ { + ans += reward2[idx[i]] + } + return +} +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution.cpp b/solution/2600-2699/2611.Mice and Cheese/Solution.cpp new file mode 100644 index 0000000000000..959893b38f8fa --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int miceAndCheese(vector& reward1, vector& reward2, int k) { + int n = reward1.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return reward1[j] - reward2[j] < reward1[i] - reward2[i]; }); + int ans = 0; + for (int i = 0; i < k; ++i) { + ans += reward1[idx[i]]; + } + for (int i = k; i < n; ++i) { + ans += reward2[idx[i]]; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution.go b/solution/2600-2699/2611.Mice and Cheese/Solution.go new file mode 100644 index 0000000000000..73eb223ed293a --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution.go @@ -0,0 +1,18 @@ +func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { + n := len(reward1) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { + i, j = idx[i], idx[j] + return reward1[j]-reward2[j] < reward1[i]-reward2[i] + }) + for i := 0; i < k; i++ { + ans += reward1[idx[i]] + } + for i := k; i < n; i++ { + ans += reward2[idx[i]] + } + return +} \ No newline at end of file diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution.java b/solution/2600-2699/2611.Mice and Cheese/Solution.java new file mode 100644 index 0000000000000..ddcda831b5914 --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution.java @@ -0,0 +1,18 @@ +class Solution { + public int miceAndCheese(int[] reward1, int[] reward2, int k) { + int n = reward1.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> reward1[j] - reward2[j] - (reward1[i] - reward2[i])); + int ans = 0; + for (int i = 0; i < k; ++i) { + ans += reward1[idx[i]]; + } + for (int i = k; i < n; ++i) { + ans += reward2[idx[i]]; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2611.Mice and Cheese/Solution.py b/solution/2600-2699/2611.Mice and Cheese/Solution.py new file mode 100644 index 0000000000000..b19f21e406c76 --- /dev/null +++ b/solution/2600-2699/2611.Mice and Cheese/Solution.py @@ -0,0 +1,6 @@ +class Solution: + def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: + n = len(reward1) + idx = sorted( + range(n), key=lambda i: reward1[i] - reward2[i], reverse=True) + return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:]) diff --git a/solution/2600-2699/2612.Minimum Reverse Operations/README.md b/solution/2600-2699/2612.Minimum Reverse Operations/README.md new file mode 100644 index 0000000000000..0d75eb76d5e61 --- /dev/null +++ b/solution/2600-2699/2612.Minimum Reverse Operations/README.md @@ -0,0 +1,157 @@ +# [2612. 最少翻转操作数](https://leetcode.cn/problems/minimum-reverse-operations) + +[English Version](/solution/2600-2699/2612.Minimum%20Reverse%20Operations/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n 和一个在范围 [0, n - 1] 以内的整数 p ,它们表示一个长度为 n 且下标从 0 开始的数组 arr ,数组中除了下标为 p 处是 1 以外,其他所有数都是 0 。

    + +

    同时给你一个整数数组 banned ,它包含数组中的一些位置。banned 中第 i 个位置表示 arr[banned[i]] = 0 ,题目保证 banned[i] != p 。

    + +

    你可以对 arr 进行 若干次 操作。一次操作中,你选择大小为 k 的一个 子数组 ,并将它 翻转 。在任何一次翻转操作后,你都需要确保 arr 中唯一的 1 不会到达任何 banned 中的位置。换句话说,arr[banned[i]] 始终 保持 0 。

    + +

    请你返回一个数组 ans ,对于 [0, n - 1] 之间的任意下标 i ,ans[i] 是将 1 放到位置 i 处的 最少 翻转操作次数,如果无法放到位置 i 处,此数为 -1 。

    + +
      +
    • 子数组 指的是一个数组里一段连续 非空 的元素序列。
    • +
    • 对于所有的 i ,ans[i] 相互之间独立计算。
    • +
    • 将一个数组中的元素 翻转 指的是将数组中的值变成 相反顺序 。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:n = 4, p = 0, banned = [1,2], k = 4
    +输出:[0,-1,-1,1]
    +解释:k = 4,所以只有一种可行的翻转操作,就是将整个数组翻转。一开始 1 在位置 0 处,所以将它翻转到位置 0 处需要的操作数为 0 。
    +我们不能将 1 翻转到 banned 中的位置,所以位置 1 和 2 处的答案都是 -1 。
    +通过一次翻转操作,可以将 1 放到位置 3 处,所以位置 3 的答案是 1 。
    +
    + +

    示例 2:

    + +
    +输入:n = 5, p = 0, banned = [2,4], k = 3
    +输出:[0,-1,-1,-1,-1]
    +解释:这个例子中 1 一开始在位置 0 处,所以此下标的答案为 0 。
    +翻转的子数组长度为 k = 3 ,1 此时在位置 0 处,所以我们可以翻转子数组 [0, 2],但翻转后的下标 2 在 banned 中,所以不能执行此操作。
    +由于 1 没法离开位置 0 ,所以其他位置的答案都是 -1 。
    +
    + +

    示例 3:

    + +
    +输入:n = 4, p = 2, banned = [0,1,3], k = 1
    +输出:[-1,-1,0,-1]
    +解释:这个例子中,我们只能对长度为 1 的子数组执行翻转操作,所以 1 无法离开初始位置。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 105
    • +
    • 0 <= p <= n - 1
    • +
    • 0 <= banned.length <= n - 1
    • +
    • 0 <= banned[i] <= n - 1
    • +
    • 1 <= k <= n 
    • +
    • banned[i] != p
    • +
    • banned 中的值 互不相同 。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +from sortedcontainers import SortedSet + + +class Solution: + def minReverseOperations(self, n: int, p: int, banned: List[int], k: int) -> List[int]: + ans = [-1] * n + ans[p] = 0 + ts = [SortedSet() for _ in range(2)] + for i in range(n): + ts[i % 2].add(i) + ts[p % 2].remove(p) + for i in banned: + ts[i % 2].remove(i) + q = deque([p]) + while q: + x = q.popleft() + i = abs(x - k + 1) + j = ts[i % 2].bisect_left(i) + while j < len(ts[i % 2]) and ts[i % 2][j] < n - abs(n - x - k): + q.append(ts[i % 2][j]) + ans[ts[i % 2][j]] = ans[x] + 1 + ts[i % 2].remove(ts[i % 2][j]) + j = ts[i % 2].bisect_left(i) + return ans +``` + +### **Java** + + + +```java +class Solution { + public int[] minReverseOperations(int n, int p, int[] banned, int k) { + int[] ans = new int[n]; + TreeSet[] ts = new TreeSet[] {new TreeSet<>(), new TreeSet<>()}; + for (int i = 0; i < n; ++i) { + ts[i % 2].add(i); + ans[i] = i == p ? 0 : -1; + } + ts[p % 2].remove(p); + for (int i : banned) { + ts[i % 2].remove(i); + } + Deque q = new ArrayDeque<>(); + q.offer(p); + while (!q.isEmpty()) { + int x = q.poll(); + int i = Math.abs(x - k + 1); + Integer j = ts[i % 2].ceiling(i); + while (j != null && j < n - Math.abs(n - x - k)) { + q.offer(j); + ans[j] = ans[x] + 1; + ts[i % 2].remove(j); + j = ts[i % 2].higher(j); + } + } + return ans; + } +} +``` + +### **C++** + +```cpp + +``` + +### **Go** + +```go + +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2612.Minimum Reverse Operations/README_EN.md b/solution/2600-2699/2612.Minimum Reverse Operations/README_EN.md new file mode 100644 index 0000000000000..18d0f606b03bb --- /dev/null +++ b/solution/2600-2699/2612.Minimum Reverse Operations/README_EN.md @@ -0,0 +1,143 @@ +# [2612. Minimum Reverse Operations](https://leetcode.com/problems/minimum-reverse-operations) + +[中文文档](/solution/2600-2699/2612.Minimum%20Reverse%20Operations/README.md) + +## Description + +

    You are given an integer n and an integer p in the range [0, n - 1]. Representing a 0-indexed array arr of length n where all positions are set to 0's, except position p which is set to 1.

    + +

    You are also given an integer array banned containing some positions from the array. For the ith position in banned, arr[banned[i]] = 0, and banned[i] != p.

    + +

    You can perform multiple operations on arr. In an operation, you can choose a subarray with size k and reverse the subarray. However, the 1 in arr should never go to any of the positions in banned. In other words, after each operation arr[banned[i]] remains 0.

    + +

    Return an array ans where for each i from [0, n - 1], ans[i] is the minimum number of reverse operations needed to bring the 1 to position i in arr, or -1 if it is impossible.

    + +
      +
    • A subarray is a contiguous non-empty sequence of elements within an array.
    • +
    • The values of ans[i] are independent for all i's.
    • +
    • The reverse of an array is an array containing the values in reverse order.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: n = 4, p = 0, banned = [1,2], k = 4
    +Output: [0,-1,-1,1]
    +Explanation: In this case k = 4 so there is only one possible reverse operation we can perform, which is reversing the whole array. Initially, 1 is placed at position 0 so the amount of operations we need for position 0 is 0. We can never place a 1 on the banned positions, so the answer for positions 1 and 2 is -1. Finally, with one reverse operation we can bring the 1 to index 3, so the answer for position 3 is 1. 
    +
    + +

    Example 2:

    + +
    +Input: n = 5, p = 0, banned = [2,4], k = 3
    +Output: [0,-1,-1,-1,-1]
    +Explanation: In this case the 1 is initially at position 0, so the answer for that position is 0. We can perform reverse operations of size 3. The 1 is currently located at position 0, so we need to reverse the subarray [0, 2] for it to leave that position, but reversing that subarray makes position 2 have a 1, which shouldn't happen. So, we can't move the 1 from position 0, making the result for all the other positions -1. 
    +
    + +

    Example 3:

    + +
    +Input: n = 4, p = 2, banned = [0,1,3], k = 1
    +Output: [-1,-1,0,-1]
    +Explanation: In this case we can only perform reverse operations of size 1. So the 1 never changes its position.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 105
    • +
    • 0 <= p <= n - 1
    • +
    • 0 <= banned.length <= n - 1
    • +
    • 0 <= banned[i] <= n - 1
    • +
    • 1 <= k <= n 
    • +
    • banned[i] != p
    • +
    • all values in banned are unique 
    • +
    + +## Solutions + + + +### **Python3** + +```python +from sortedcontainers import SortedSet + + +class Solution: + def minReverseOperations(self, n: int, p: int, banned: List[int], k: int) -> List[int]: + ans = [-1] * n + ans[p] = 0 + ts = [SortedSet() for _ in range(2)] + for i in range(n): + ts[i % 2].add(i) + ts[p % 2].remove(p) + for i in banned: + ts[i % 2].remove(i) + q = deque([p]) + while q: + x = q.popleft() + i = abs(x - k + 1) + j = ts[i % 2].bisect_left(i) + while j < len(ts[i % 2]) and ts[i % 2][j] < n - abs(n - x - k): + q.append(ts[i % 2][j]) + ans[ts[i % 2][j]] = ans[x] + 1 + ts[i % 2].remove(ts[i % 2][j]) + j = ts[i % 2].bisect_left(i) + return ans +``` + +### **Java** + +```java +class Solution { + public int[] minReverseOperations(int n, int p, int[] banned, int k) { + int[] ans = new int[n]; + TreeSet[] ts = new TreeSet[] {new TreeSet<>(), new TreeSet<>()}; + for (int i = 0; i < n; ++i) { + ts[i % 2].add(i); + ans[i] = i == p ? 0 : -1; + } + ts[p % 2].remove(p); + for (int i : banned) { + ts[i % 2].remove(i); + } + Deque q = new ArrayDeque<>(); + q.offer(p); + while (!q.isEmpty()) { + int x = q.poll(); + int i = Math.abs(x - k + 1); + Integer j = ts[i % 2].ceiling(i); + while (j != null && j < n - Math.abs(n - x - k)) { + q.offer(j); + ans[j] = ans[x] + 1; + ts[i % 2].remove(j); + j = ts[i % 2].higher(j); + } + } + return ans; + } +} +``` + +### **C++** + +```cpp + +``` + +### **Go** + +```go + +``` + +### **...** + +``` + +``` + + diff --git a/solution/2600-2699/2612.Minimum Reverse Operations/Solution.java b/solution/2600-2699/2612.Minimum Reverse Operations/Solution.java new file mode 100644 index 0000000000000..60ea0f54aed2c --- /dev/null +++ b/solution/2600-2699/2612.Minimum Reverse Operations/Solution.java @@ -0,0 +1,28 @@ +class Solution { + public int[] minReverseOperations(int n, int p, int[] banned, int k) { + int[] ans = new int[n]; + TreeSet[] ts = new TreeSet[] {new TreeSet<>(), new TreeSet<>()}; + for (int i = 0; i < n; ++i) { + ts[i % 2].add(i); + ans[i] = i == p ? 0 : -1; + } + ts[p % 2].remove(p); + for (int i : banned) { + ts[i % 2].remove(i); + } + Deque q = new ArrayDeque<>(); + q.offer(p); + while (!q.isEmpty()) { + int x = q.poll(); + int i = Math.abs(x - k + 1); + Integer j = ts[i % 2].ceiling(i); + while (j != null && j < n - Math.abs(n - x - k)) { + q.offer(j); + ans[j] = ans[x] + 1; + ts[i % 2].remove(j); + j = ts[i % 2].higher(j); + } + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2600-2699/2612.Minimum Reverse Operations/Solution.py b/solution/2600-2699/2612.Minimum Reverse Operations/Solution.py new file mode 100644 index 0000000000000..cd27db203a203 --- /dev/null +++ b/solution/2600-2699/2612.Minimum Reverse Operations/Solution.py @@ -0,0 +1,24 @@ +from sortedcontainers import SortedSet + + +class Solution: + def minReverseOperations(self, n: int, p: int, banned: List[int], k: int) -> List[int]: + ans = [-1] * n + ans[p] = 0 + ts = [SortedSet() for _ in range(2)] + for i in range(n): + ts[i % 2].add(i) + ts[p % 2].remove(p) + for i in banned: + ts[i % 2].remove(i) + q = deque([p]) + while q: + x = q.popleft() + i = abs(x - k + 1) + j = ts[i % 2].bisect_left(i) + while j < len(ts[i % 2]) and ts[i % 2][j] < n - abs(n - x - k): + q.append(ts[i % 2][j]) + ans[ts[i % 2][j]] = ans[x] + 1 + ts[i % 2].remove(ts[i % 2][j]) + j = ts[i % 2].bisect_left(i) + return ans diff --git a/solution/CONTEST_README.md b/solution/CONTEST_README.md index 1b204d626fcb3..461e14587c681 100644 --- a/solution/CONTEST_README.md +++ b/solution/CONTEST_README.md @@ -24,6 +24,14 @@ ## 往期竞赛 +#### 第 339 场周赛(2023-04-02 10:30, 90 分钟) 参赛人数 5180 + +- [2609. 最长平衡子字符串](/solution/2600-2699/2609.Find%20the%20Longest%20Balanced%20Substring%20of%20a%20Binary%20String/README.md) +- [2610. 转换二维数组](/solution/2600-2699/2610.Convert%20an%20Array%20Into%20a%202D%20Array%20With%20Conditions/README.md) +- [2611. 老鼠和奶酪](/solution/2600-2699/2611.Mice%20and%20Cheese/README.md) +- [2612. 最少翻转操作数](/solution/2600-2699/2612.Minimum%20Reverse%20Operations/README.md) + + #### 第 101 场双周赛(2023-04-01 22:30, 90 分钟) 参赛人数 3353 - [2605. 从两个数字数组里生成最小数字](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README.md) diff --git a/solution/CONTEST_README_EN.md b/solution/CONTEST_README_EN.md index 6ed87c1f97f8e..268b5a64dd72a 100644 --- a/solution/CONTEST_README_EN.md +++ b/solution/CONTEST_README_EN.md @@ -25,6 +25,14 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## Past Contests +#### Weekly Contest 339 + +- [2609. Find the Longest Balanced Substring of a Binary String](/solution/2600-2699/2609.Find%20the%20Longest%20Balanced%20Substring%20of%20a%20Binary%20String/README_EN.md) +- [2610. Convert an Array Into a 2D Array With Conditions](/solution/2600-2699/2610.Convert%20an%20Array%20Into%20a%202D%20Array%20With%20Conditions/README_EN.md) +- [2611. Mice and Cheese](/solution/2600-2699/2611.Mice%20and%20Cheese/README_EN.md) +- [2612. Minimum Reverse Operations](/solution/2600-2699/2612.Minimum%20Reverse%20Operations/README_EN.md) + + #### Biweekly Contest 101 - [2605. Form Smallest Number From Two Digit Arrays](/solution/2600-2699/2605.Form%20Smallest%20Number%20From%20Two%20Digit%20Arrays/README_EN.md) diff --git a/solution/README.md b/solution/README.md index a7ca4ed6aa99b..39b88f35e5249 100644 --- a/solution/README.md +++ b/solution/README.md @@ -2619,6 +2619,10 @@ | 2606 | [找到最大开销的子字符串](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README.md) | | 中等 | 第 101 场双周赛 | | 2607 | [使子数组元素和相等](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README.md) | | 中等 | 第 101 场双周赛 | | 2608 | [图中的最短环](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README.md) | | 困难 | 第 101 场双周赛 | +| 2609 | [最长平衡子字符串](/solution/2600-2699/2609.Find%20the%20Longest%20Balanced%20Substring%20of%20a%20Binary%20String/README.md) | | 简单 | 第 339 场周赛 | +| 2610 | [转换二维数组](/solution/2600-2699/2610.Convert%20an%20Array%20Into%20a%202D%20Array%20With%20Conditions/README.md) | | 中等 | 第 339 场周赛 | +| 2611 | [老鼠和奶酪](/solution/2600-2699/2611.Mice%20and%20Cheese/README.md) | | 中等 | 第 339 场周赛 | +| 2612 | [最少翻转操作数](/solution/2600-2699/2612.Minimum%20Reverse%20Operations/README.md) | | 困难 | 第 339 场周赛 | ## 版权 diff --git a/solution/README_EN.md b/solution/README_EN.md index 53f28a66c9b33..0a2972d220cae 100644 --- a/solution/README_EN.md +++ b/solution/README_EN.md @@ -2617,6 +2617,10 @@ Press Control+F(or Command+F on the | 2606 | [Find the Substring With Maximum Cost](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README_EN.md) | | Medium | Biweekly Contest 101 | | 2607 | [Make K-Subarray Sums Equal](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README_EN.md) | | Medium | Biweekly Contest 101 | | 2608 | [Shortest Cycle in a Graph](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README_EN.md) | | Hard | Biweekly Contest 101 | +| 2609 | [Find the Longest Balanced Substring of a Binary String](/solution/2600-2699/2609.Find%20the%20Longest%20Balanced%20Substring%20of%20a%20Binary%20String/README_EN.md) | | Easy | Weekly Contest 339 | +| 2610 | [Convert an Array Into a 2D Array With Conditions](/solution/2600-2699/2610.Convert%20an%20Array%20Into%20a%202D%20Array%20With%20Conditions/README_EN.md) | | Medium | Weekly Contest 339 | +| 2611 | [Mice and Cheese](/solution/2600-2699/2611.Mice%20and%20Cheese/README_EN.md) | | Medium | Weekly Contest 339 | +| 2612 | [Minimum Reverse Operations](/solution/2600-2699/2612.Minimum%20Reverse%20Operations/README_EN.md) | | Hard | Weekly Contest 339 | ## Copyright diff --git a/solution/summary.md b/solution/summary.md index 5c6050fad9990..b910a47344fe7 100644 --- a/solution/summary.md +++ b/solution/summary.md @@ -2660,3 +2660,7 @@ - [2606.找到最大开销的子字符串](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README.md) - [2607.使子数组元素和相等](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README.md) - [2608.图中的最短环](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README.md) + - [2609.最长平衡子字符串](/solution/2600-2699/2609.Find%20the%20Longest%20Balanced%20Substring%20of%20a%20Binary%20String/README.md) + - [2610.转换二维数组](/solution/2600-2699/2610.Convert%20an%20Array%20Into%20a%202D%20Array%20With%20Conditions/README.md) + - [2611.老鼠和奶酪](/solution/2600-2699/2611.Mice%20and%20Cheese/README.md) + - [2612.最少翻转操作数](/solution/2600-2699/2612.Minimum%20Reverse%20Operations/README.md) diff --git a/solution/summary_en.md b/solution/summary_en.md index 847f56dcb01c3..5b8cf8788adda 100644 --- a/solution/summary_en.md +++ b/solution/summary_en.md @@ -2660,3 +2660,7 @@ - [2606.Find the Substring With Maximum Cost](/solution/2600-2699/2606.Find%20the%20Substring%20With%20Maximum%20Cost/README_EN.md) - [2607.Make K-Subarray Sums Equal](/solution/2600-2699/2607.Make%20K-Subarray%20Sums%20Equal/README_EN.md) - [2608.Shortest Cycle in a Graph](/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/README_EN.md) + - [2609.Find the Longest Balanced Substring of a Binary String](/solution/2600-2699/2609.Find%20the%20Longest%20Balanced%20Substring%20of%20a%20Binary%20String/README_EN.md) + - [2610.Convert an Array Into a 2D Array With Conditions](/solution/2600-2699/2610.Convert%20an%20Array%20Into%20a%202D%20Array%20With%20Conditions/README_EN.md) + - [2611.Mice and Cheese](/solution/2600-2699/2611.Mice%20and%20Cheese/README_EN.md) + - [2612.Minimum Reverse Operations](/solution/2600-2699/2612.Minimum%20Reverse%20Operations/README_EN.md) From 4868f8d64a50ba24f31a745ae319d7f27d862e04 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Sun, 2 Apr 2023 16:36:36 +0800 Subject: [PATCH 3/3] feat: add solutions to lc problem: No.2605 No.2605.Form Smallest Number From Two Digit Arrays --- .../README.md | 205 ++++++++++++++++++ .../README_EN.md | 183 ++++++++++++++++ 2 files changed, 388 insertions(+) diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md index df5a95b0aeb3b..d68811e583ec5 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md @@ -38,6 +38,28 @@ +**方法一:枚举** + +我们观察发现,如果数组 $nums1$ 和 $nums2$ 中有相同的数字,那么相同数字中的最小值一定是最小的数字。否则我们取 $nums1$ 中的数字 $a$ 和 $nums2$ 中的数字 $b$,将 $a$ 和 $b$ 拼接成两个数字,取其中较小的数字即可。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度。 + +**方法二:哈希表或数组 + 枚举** + +我们可以用哈希表或数组记录数组 $nums1$ 和 $nums2$ 中的数字,然后枚举 $1 \sim 9$,如果 $i$ 在两个数组中都出现了,那么 $i$ 就是最小的数字。否则我们取 $nums1$ 中的数字 $a$ 和 $nums2$ 中的数字 $b$,将 $a$ 和 $b$ 拼接成两个数字,取其中较小的数字即可。 + +时间复杂度 $(m + n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度;而 $C$ 是数组 $nums1$ 和 $nums2$ 中数字的范围,本题中 $C = 10$。 + +**方法三:位运算** + +由于数字的范围是 $1 \sim 9$,我们可以用一个长度为 $10$ 的二进制数来表示数组 $nums1$ 和 $nums2$ 中的数字。我们用 $mask1$ 表示数组 $nums1$ 中的数字,用 $mask2$ 表示数组 $nums2$ 中的数字。 + +如果 $mask1$ 和 $mask2$ 进行按位与得到的数字 $mask$ 不等于 $0$,那么我们提取 $mask$ 中最后一位 $1$ 所在的位置,即为最小的数字。 + +否则,我们分别提取 $mask1$ 和 $mask2$ 中最后一位 $1$ 所在的位置,分别记为 $a$ 和 $b$,那么最小的数字就是 $min(a \times 10 + b, b \times 10 + a)$。 + +时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度。 + ### **Python3** @@ -57,6 +79,32 @@ class Solution: return ans ``` +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + s = set(nums1) & set(nums2) + if s: + return min(s) + a, b = min(nums1), min(nums2) + return min(a * 10 + b, b * 10 + a) +``` + +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + mask1 = mask2 = 0 + for x in nums1: + mask1 |= 1 << x + for x in nums2: + mask2 |= 1 << x + mask = mask1 & mask2 + if mask: + return (mask & -mask).bit_length() - 1 + a = (mask1 & -mask1).bit_length() - 1 + b = (mask2 & -mask2).bit_length() - 1 + return min(a * 10 + b, b * 10 + a) +``` + ### **Java** @@ -79,6 +127,55 @@ class Solution { } ``` +```java +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + boolean[] s1 = new boolean[10]; + boolean[] s2 = new boolean[10]; + for (int x : nums1) { + s1[x] = true; + } + for (int x : nums2) { + s2[x] = true; + } + int a = 0, b = 0; + for (int i = 1; i < 10; ++i) { + if (s1[i] && s2[i]) { + return i; + } + if (a == 0 && s1[i]) { + a = i; + } + if (b == 0 && s2[i]) { + b = i; + } + } + return Math.min(a * 10 + b, b * 10 + a); + } +} +``` + +```java +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask != 0) { + return Integer.numberOfTrailingZeros(mask); + } + int a = Integer.numberOfTrailingZeros(mask1); + int b = Integer.numberOfTrailingZeros(mask2); + return Math.min(a * 10 + b, b * 10 + a); + } +} +``` + ### **C++** ```cpp @@ -100,6 +197,57 @@ public: }; ``` +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + bitset<10> s1; + bitset<10> s2; + for (int x : nums1) { + s1[x] = 1; + } + for (int x : nums2) { + s2[x] = 1; + } + int a = 0, b = 0; + for (int i = 1; i < 10; ++i) { + if (s1[i] && s2[i]) { + return i; + } + if (!a && s1[i]) { + a = i; + } + if (!b && s2[i]) { + b = i; + } + } + return min(a * 10 + b, b * 10 + a); + } +}; +``` + +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask) { + return __builtin_ctz(mask); + } + int a = __builtin_ctz(mask1); + int b = __builtin_ctz(mask2); + return min(a * 10 + b, b * 10 + a); + } +}; +``` + ### **Go** ```go @@ -125,6 +273,63 @@ func min(a, b int) int { } ``` +```go +func minNumber(nums1 []int, nums2 []int) int { + s1 := [10]bool{} + s2 := [10]bool{} + for _, x := range nums1 { + s1[x] = true + } + for _, x := range nums2 { + s2[x] = true + } + a, b := 0, 0 + for i := 1; i < 10; i++ { + if s1[i] && s2[i] { + return i + } + if a == 0 && s1[i] { + a = i + } + if b == 0 && s2[i] { + b = i + } + } + return min(a*10+b, b*10+a) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +```go +func minNumber(nums1 []int, nums2 []int) int { + var mask1, mask2 uint + for _, x := range nums1 { + mask1 |= 1 << x + } + for _, x := range nums2 { + mask2 |= 1 << x + } + if mask := mask1 & mask2; mask != 0 { + return bits.TrailingZeros(mask) + } + a, b := bits.TrailingZeros(mask1), bits.TrailingZeros(mask2) + return min(a*10+b, b*10+a) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md index 0fb48ae681a0a..9b2a611786507 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md @@ -51,6 +51,32 @@ class Solution: return ans ``` +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + s = set(nums1) & set(nums2) + if s: + return min(s) + a, b = min(nums1), min(nums2) + return min(a * 10 + b, b * 10 + a) +``` + +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + mask1 = mask2 = 0 + for x in nums1: + mask1 |= 1 << x + for x in nums2: + mask2 |= 1 << x + mask = mask1 & mask2 + if mask: + return (mask & -mask).bit_length() - 1 + a = (mask1 & -mask1).bit_length() - 1 + b = (mask2 & -mask2).bit_length() - 1 + return min(a * 10 + b, b * 10 + a) +``` + ### **Java** ```java @@ -71,6 +97,55 @@ class Solution { } ``` +```java +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + boolean[] s1 = new boolean[10]; + boolean[] s2 = new boolean[10]; + for (int x : nums1) { + s1[x] = true; + } + for (int x : nums2) { + s2[x] = true; + } + int a = 0, b = 0; + for (int i = 1; i < 10; ++i) { + if (s1[i] && s2[i]) { + return i; + } + if (a == 0 && s1[i]) { + a = i; + } + if (b == 0 && s2[i]) { + b = i; + } + } + return Math.min(a * 10 + b, b * 10 + a); + } +} +``` + +```java +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask != 0) { + return Integer.numberOfTrailingZeros(mask); + } + int a = Integer.numberOfTrailingZeros(mask1); + int b = Integer.numberOfTrailingZeros(mask2); + return Math.min(a * 10 + b, b * 10 + a); + } +} +``` + ### **C++** ```cpp @@ -92,6 +167,57 @@ public: }; ``` +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + bitset<10> s1; + bitset<10> s2; + for (int x : nums1) { + s1[x] = 1; + } + for (int x : nums2) { + s2[x] = 1; + } + int a = 0, b = 0; + for (int i = 1; i < 10; ++i) { + if (s1[i] && s2[i]) { + return i; + } + if (!a && s1[i]) { + a = i; + } + if (!b && s2[i]) { + b = i; + } + } + return min(a * 10 + b, b * 10 + a); + } +}; +``` + +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask) { + return __builtin_ctz(mask); + } + int a = __builtin_ctz(mask1); + int b = __builtin_ctz(mask2); + return min(a * 10 + b, b * 10 + a); + } +}; +``` + ### **Go** ```go @@ -117,6 +243,63 @@ func min(a, b int) int { } ``` +```go +func minNumber(nums1 []int, nums2 []int) int { + s1 := [10]bool{} + s2 := [10]bool{} + for _, x := range nums1 { + s1[x] = true + } + for _, x := range nums2 { + s2[x] = true + } + a, b := 0, 0 + for i := 1; i < 10; i++ { + if s1[i] && s2[i] { + return i + } + if a == 0 && s1[i] { + a = i + } + if b == 0 && s2[i] { + b = i + } + } + return min(a*10+b, b*10+a) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +```go +func minNumber(nums1 []int, nums2 []int) int { + var mask1, mask2 uint + for _, x := range nums1 { + mask1 |= 1 << x + } + for _, x := range nums2 { + mask2 |= 1 << x + } + if mask := mask1 & mask2; mask != 0 { + return bits.TrailingZeros(mask) + } + a, b := bits.TrailingZeros(mask1), bits.TrailingZeros(mask2) + return min(a*10+b, b*10+a) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + ### **...** ```