From 6bede492db9085baf9452bd20613e6f221ed2eae Mon Sep 17 00:00:00 2001 From: Herschel Date: Sun, 10 Dec 2023 20:40:49 +0800 Subject: [PATCH 1/2] feat: add solution to lc problem: No.38 && fix: title to No.32 (#2079) --- .../0032.Longest Valid Parentheses/README.md | 2 +- .../README_EN.md | 2 +- .../0000-0099/0038.Count and Say/README.md | 40 +++++++++++++++++++ .../0000-0099/0038.Count and Say/README_EN.md | 40 +++++++++++++++++++ .../0000-0099/0038.Count and Say/Solution.rs | 22 ++++++++++ 5 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 solution/0000-0099/0038.Count and Say/Solution.rs diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/README.md b/solution/0000-0099/0032.Longest Valid Parentheses/README.md index ce178465d30da..ccb3aa2c2a2e4 100644 --- a/solution/0000-0099/0032.Longest Valid Parentheses/README.md +++ b/solution/0000-0099/0032.Longest Valid Parentheses/README.md @@ -341,7 +341,7 @@ var longestValidParentheses = function (s) { }; ``` -### Rust +### **Rust** ```rust impl Solution { diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/README_EN.md b/solution/0000-0099/0032.Longest Valid Parentheses/README_EN.md index e4d4b974df5e9..cea5ab48538eb 100644 --- a/solution/0000-0099/0032.Longest Valid Parentheses/README_EN.md +++ b/solution/0000-0099/0032.Longest Valid Parentheses/README_EN.md @@ -332,7 +332,7 @@ var longestValidParentheses = function (s) { }; ``` -### Rust +### **Rust** ```rust impl Solution { diff --git a/solution/0000-0099/0038.Count and Say/README.md b/solution/0000-0099/0038.Count and Say/README.md index a4e96b3a88f8f..99c5aa8ebde2d 100644 --- a/solution/0000-0099/0038.Count and Say/README.md +++ b/solution/0000-0099/0038.Count and Say/README.md @@ -71,6 +71,20 @@ countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211" ## 解法 +**方法一: 模拟** + +题目要求输出第 $n$ 项的外观序列,而第 $n$ 项是序列中第 $n-1$ 项的描述。所以我们遍历 $n-1$ 次,每次迭代用快慢指针j和i,分别记录当前字符的位置以及下一个不等于当前字符的位置,更新上一项的序列为 $j-i$ 个当前字符。 + +时间复杂度: + +1. 外部循环迭代 `for _ in range(n - 1)`,这会执行 `n-1` 次。 +2. 在内部循环中,我们遍历了字符串`s`, 长度最大为上一项的长度。 +3. 内部循环嵌套循环执行了一些基本操作,如比较和字符串拼接,这些基本操作的复杂度可以视为 $O(1)$ 。 + +综合考虑,整体时间复杂度为 $O(n \times m)$, 其中 n 是要生成的序列的项数, m 是前一项的最大长度。 + +空间复杂度: $O(m)$, 其中 m 是前一项的最大长度。 + @@ -260,6 +274,32 @@ function countAndSay(n: number): string { } ``` +### **Rust** + +```rust +use std::iter::once; + +impl Solution { + pub fn count_and_say(n: i32) -> String { + (1..n) + .fold(vec![1], |curr, _| { + let mut next = vec![]; + let mut slow = 0; + for fast in 0..=curr.len() { + if fast == curr.len() || curr[slow] != curr[fast] { + next.extend(once((fast - slow) as u8).chain(once(curr[slow]))); + slow = fast; + } + } + next + }) + .into_iter() + .map(|digit| (digit + b'0') as char) + .collect() + } +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0038.Count and Say/README_EN.md b/solution/0000-0099/0038.Count and Say/README_EN.md index 62eaea3da8ed0..5157477bb886a 100644 --- a/solution/0000-0099/0038.Count and Say/README_EN.md +++ b/solution/0000-0099/0038.Count and Say/README_EN.md @@ -47,6 +47,20 @@ countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11& ## Solutions +**Solution 1: Simulation** + +The task requires outputting the appearance sequence of the $n$-th item, where the $n$-th item is the description of the $n-1$-th item in the sequence. Therefore, we iterate $n-1$ times. In each iteration, we use fast and slow pointers, denoted as j and i respectively, to record the current character's position and the position of the next character that is not equal to the current character. We then update the sequence of the previous item to be $j-i$ occurrences of the current character. + +Time Complexity: + +1. The outer loop runs `n - 1` times, iterating to generate the "Count and Say" sequence up to the nth term. +2. The inner while loop iterates through each character in the current string s and counts the consecutive occurrences of the same character. +3. The inner while loop runs in $O(m)$ time, where m is the length of the current string s. + +Overall, the time complexity is $O(n \times m)$, where n is the input parameter representing the term to generate, and m is the maximum length of the string in the sequence. + +Space Complexity: $O(m)$. + ### **Python3** @@ -230,6 +244,32 @@ function countAndSay(n: number): string { } ``` +### **Rust** + +```rust +use std::iter::once; + +impl Solution { + pub fn count_and_say(n: i32) -> String { + (1..n) + .fold(vec![1], |curr, _| { + let mut next = vec![]; + let mut slow = 0; + for fast in 0..=curr.len() { + if fast == curr.len() || curr[slow] != curr[fast] { + next.extend(once((fast - slow) as u8).chain(once(curr[slow]))); + slow = fast; + } + } + next + }) + .into_iter() + .map(|digit| (digit + b'0') as char) + .collect() + } +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0038.Count and Say/Solution.rs b/solution/0000-0099/0038.Count and Say/Solution.rs new file mode 100644 index 0000000000000..e6a11b4d3ffaf --- /dev/null +++ b/solution/0000-0099/0038.Count and Say/Solution.rs @@ -0,0 +1,22 @@ +use std::iter::once; + +impl Solution { + pub fn count_and_say(n: i32) -> String { + (1..n) + .fold(vec![1], |curr, _| { + let mut next = vec![]; + let mut slow = 0; + for fast in 0..=curr.len() { + if fast == curr.len() || curr[slow] != curr[fast] { + next.extend(once((fast - slow) as u8).chain(once(curr[slow]))); + slow = fast; + } + } + next + }) + .into_iter() + .map(|digit| (digit + b'0') as char) + .collect() + } +} + From 0105c269c452c12d9dd3dd82182bd0320e98925d Mon Sep 17 00:00:00 2001 From: Libin YANG Date: Sun, 10 Dec 2023 20:43:32 +0800 Subject: [PATCH 2/2] feat: add solutions to lc problem: No.2958 (#2080) No.2958.Length of Longest Subarray With at Most K Frequency --- .../README.md | 78 ++++++++++++++++++- .../README_EN.md | 78 ++++++++++++++++++- .../Solution.cpp | 15 ++++ .../Solution.go | 11 +++ .../Solution.java | 14 ++++ .../Solution.py | 11 +++ .../Solution.ts | 12 +++ 7 files changed, 213 insertions(+), 6 deletions(-) create mode 100644 solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.cpp create mode 100644 solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.go create mode 100644 solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.java create mode 100644 solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.py create mode 100644 solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.ts diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README.md b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README.md index b8f52ded28f1f..f5d1c51dd2403 100644 --- a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README.md +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README.md @@ -59,6 +59,14 @@ +**方法一:双指针** + +我们可以用两个指针 $j$ 和 $i$ 分别表示子数组的左右端点,初始时两个指针都指向数组的第一个元素。 + +接下来,我们遍历数组 $nums$ 中的每个元素 $x$,对于每个元素 $x$,我们将 $x$ 的出现次数加一,然后判断当前子数组是否满足要求。如果当前子数组不满足要求,我们就将指针 $j$ 右移一位,并将 $nums[j]$ 的出现次数减一,直到当前子数组满足要求为止。然后我们更新答案 $ans = \max(ans, i - j + 1)$。继续遍历,直到 $i$ 到达数组的末尾。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 + ### **Python3** @@ -66,7 +74,17 @@ ```python - +class Solution: + def maxSubarrayLength(self, nums: List[int], k: int) -> int: + cnt = defaultdict(int) + ans = j = 0 + for i, x in enumerate(nums): + cnt[x] += 1 + while cnt[x] > k: + cnt[nums[j]] -= 1 + j += 1 + ans = max(ans, i - j + 1) + return ans ``` ### **Java** @@ -74,19 +92,73 @@ ```java - +class Solution { + public int maxSubarrayLength(int[] nums, int k) { + Map cnt = new HashMap<>(); + int ans = 0; + for (int i = 0, j = 0; i < nums.length; ++i) { + cnt.merge(nums[i], 1, Integer::sum); + while (cnt.get(nums[i]) > k) { + cnt.merge(nums[j++], -1, Integer::sum); + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} ``` ### **C++** ```cpp - +class Solution { +public: + int maxSubarrayLength(vector& nums, int k) { + unordered_map cnt; + int ans = 0; + for (int i = 0, j = 0; i < nums.size(); ++i) { + ++cnt[nums[i]]; + while (cnt[nums[i]] > k) { + --cnt[nums[j++]]; + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; ``` ### **Go** ```go +func maxSubarrayLength(nums []int, k int) (ans int) { + cnt := map[int]int{} + for i, j, n := 0, 0, len(nums); i < n; i++ { + cnt[nums[i]]++ + for ; cnt[nums[i]] > k; j++ { + cnt[nums[j]]-- + } + ans = max(ans, i-j+1) + } + return +} +``` +### **TypeScript** + +```ts +function maxSubarrayLength(nums: number[], k: number): number { + const cnt: Map = new Map(); + let ans = 0; + for (let i = 0, j = 0; i < nums.length; ++i) { + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); + for (; cnt.get(nums[i])! > k; ++j) { + cnt.set(nums[j], cnt.get(nums[j])! - 1); + } + ans = Math.max(ans, i - j + 1); + } + return ans; +} ``` ### **...** diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README_EN.md b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README_EN.md index b5eec0be8447a..73f0a022003fe 100644 --- a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README_EN.md +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README_EN.md @@ -53,30 +53,102 @@ It can be shown that there are no good subarrays with length more than 4. ## Solutions +**Solution 1: Two Pointers** + +We can use two pointers $j$ and $i$ to represent the left and right endpoints of the subarray, initially both pointers point to the first element of the array. + +Next, we iterate over each element $x$ in the array $nums$. For each element $x$, we increment the occurrence count of $x$, then check if the current subarray meets the requirements. If the current subarray does not meet the requirements, we move the pointer $j$ one step to the right, and decrement the occurrence count of $nums[j]$, until the current subarray meets the requirements. Then we update the answer $ans = \max(ans, i - j + 1)$. Continue the iteration until $i$ reaches the end of the array. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + ### **Python3** ```python - +class Solution: + def maxSubarrayLength(self, nums: List[int], k: int) -> int: + cnt = defaultdict(int) + ans = j = 0 + for i, x in enumerate(nums): + cnt[x] += 1 + while cnt[x] > k: + cnt[nums[j]] -= 1 + j += 1 + ans = max(ans, i - j + 1) + return ans ``` ### **Java** ```java - +class Solution { + public int maxSubarrayLength(int[] nums, int k) { + Map cnt = new HashMap<>(); + int ans = 0; + for (int i = 0, j = 0; i < nums.length; ++i) { + cnt.merge(nums[i], 1, Integer::sum); + while (cnt.get(nums[i]) > k) { + cnt.merge(nums[j++], -1, Integer::sum); + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} ``` ### **C++** ```cpp - +class Solution { +public: + int maxSubarrayLength(vector& nums, int k) { + unordered_map cnt; + int ans = 0; + for (int i = 0, j = 0; i < nums.size(); ++i) { + ++cnt[nums[i]]; + while (cnt[nums[i]] > k) { + --cnt[nums[j++]]; + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; ``` ### **Go** ```go +func maxSubarrayLength(nums []int, k int) (ans int) { + cnt := map[int]int{} + for i, j, n := 0, 0, len(nums); i < n; i++ { + cnt[nums[i]]++ + for ; cnt[nums[i]] > k; j++ { + cnt[nums[j]]-- + } + ans = max(ans, i-j+1) + } + return +} +``` +### **TypeScript** + +```ts +function maxSubarrayLength(nums: number[], k: number): number { + const cnt: Map = new Map(); + let ans = 0; + for (let i = 0, j = 0; i < nums.length; ++i) { + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); + for (; cnt.get(nums[i])! > k; ++j) { + cnt.set(nums[j], cnt.get(nums[j])! - 1); + } + ans = Math.max(ans, i - j + 1); + } + return ans; +} ``` ### **...** diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.cpp b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.cpp new file mode 100644 index 0000000000000..56ebf61009e0f --- /dev/null +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maxSubarrayLength(vector& nums, int k) { + unordered_map cnt; + int ans = 0; + for (int i = 0, j = 0; i < nums.size(); ++i) { + ++cnt[nums[i]]; + while (cnt[nums[i]] > k) { + --cnt[nums[j++]]; + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.go b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.go new file mode 100644 index 0000000000000..df651cb700000 --- /dev/null +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.go @@ -0,0 +1,11 @@ +func maxSubarrayLength(nums []int, k int) (ans int) { + cnt := map[int]int{} + for i, j, n := 0, 0, len(nums); i < n; i++ { + cnt[nums[i]]++ + for ; cnt[nums[i]] > k; j++ { + cnt[nums[j]]-- + } + ans = max(ans, i-j+1) + } + return +} \ No newline at end of file diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.java b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.java new file mode 100644 index 0000000000000..439cce2f7efdf --- /dev/null +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.java @@ -0,0 +1,14 @@ +class Solution { + public int maxSubarrayLength(int[] nums, int k) { + Map cnt = new HashMap<>(); + int ans = 0; + for (int i = 0, j = 0; i < nums.length; ++i) { + cnt.merge(nums[i], 1, Integer::sum); + while (cnt.get(nums[i]) > k) { + cnt.merge(nums[j++], -1, Integer::sum); + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.py b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.py new file mode 100644 index 0000000000000..d60179b75cfae --- /dev/null +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.py @@ -0,0 +1,11 @@ +class Solution: + def maxSubarrayLength(self, nums: List[int], k: int) -> int: + cnt = defaultdict(int) + ans = j = 0 + for i, x in enumerate(nums): + cnt[x] += 1 + while cnt[x] > k: + cnt[nums[j]] -= 1 + j += 1 + ans = max(ans, i - j + 1) + return ans diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.ts b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.ts new file mode 100644 index 0000000000000..635f3700271e9 --- /dev/null +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/Solution.ts @@ -0,0 +1,12 @@ +function maxSubarrayLength(nums: number[], k: number): number { + const cnt: Map = new Map(); + let ans = 0; + for (let i = 0, j = 0; i < nums.length; ++i) { + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); + for (; cnt.get(nums[i])! > k; ++j) { + cnt.set(nums[j], cnt.get(nums[j])! - 1); + } + ans = Math.max(ans, i - j + 1); + } + return ans; +}