diff --git a/solution/0000-0099/0066.Plus One/README.md b/solution/0000-0099/0066.Plus One/README.md index 79fa7cbfdb0da..cebb148fafd2d 100644 --- a/solution/0000-0099/0066.Plus One/README.md +++ b/solution/0000-0099/0066.Plus One/README.md @@ -50,6 +50,12 @@ +**方法一:模拟** + +我们从数组的最后一个元素开始遍历,将当前元素加一,然后对 $10$ 取模,如果取模后的结果不为 $0$,说明当前元素没有进位,直接返回数组即可。否则,当前元素为 $0$,需要进位,继续遍历前一个元素,重复上述操作。如果遍历完数组后,仍然没有返回,说明数组中所有元素都为 $0$,需要在数组的头部插入一个 $1$。 + +时间复杂度 $O(n)$,其中 $n$ 是数组的长度。忽略答案的空间消耗,空间复杂度 $O(1)$。 + ### **Python3** diff --git a/solution/0000-0099/0066.Plus One/README_EN.md b/solution/0000-0099/0066.Plus One/README_EN.md index dbde9abe3cb54..4c0a83ae214f7 100644 --- a/solution/0000-0099/0066.Plus One/README_EN.md +++ b/solution/0000-0099/0066.Plus One/README_EN.md @@ -50,6 +50,12 @@ Thus, the result should be [1,0]. ## Solutions +**Solution 1: Simulation** + +We start traversing from the last element of the array, add one to the current element, and then take the modulus by $10$. If the result is not $0$, it means that there is no carry for the current element, and we can directly return the array. Otherwise, the current element is $0$ and needs to be carried over. We continue to traverse the previous element and repeat the above operation. If we still haven't returned after traversing the array, it means that all elements in the array are $0$, and we need to insert a $1$ at the beginning of the array. + +The time complexity is $O(n)$, where $n$ is the length of the array. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/0200-0299/0242.Valid Anagram/README.md b/solution/0200-0299/0242.Valid Anagram/README.md index 9762543aca594..6f15152936927 100644 --- a/solution/0200-0299/0242.Valid Anagram/README.md +++ b/solution/0200-0299/0242.Valid Anagram/README.md @@ -69,6 +69,12 @@ class Solution: return True ``` +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) +``` + ### **Java** diff --git a/solution/0200-0299/0242.Valid Anagram/README_EN.md b/solution/0200-0299/0242.Valid Anagram/README_EN.md index 2460524d86baf..051fd68878b1b 100644 --- a/solution/0200-0299/0242.Valid Anagram/README_EN.md +++ b/solution/0200-0299/0242.Valid Anagram/README_EN.md @@ -54,6 +54,12 @@ class Solution: return True ``` +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) +``` + ### **Java** ```java diff --git a/solution/0200-0299/0283.Move Zeroes/README_EN.md b/solution/0200-0299/0283.Move Zeroes/README_EN.md index 81bd5959f3fd6..f0af9ebd0a69b 100644 --- a/solution/0200-0299/0283.Move Zeroes/README_EN.md +++ b/solution/0200-0299/0283.Move Zeroes/README_EN.md @@ -29,6 +29,14 @@ ## Solutions +**Solution 1: Two Pointers** + +We use two pointers $i$ and $j$, where pointer $i$ points to the end of the sequence that has been processed, and pointer $j$ points to the head of the sequence to be processed. Initially, $i=-1$. + +Next, we traverse $j \in [0,n)$, if $nums[j] \neq 0$, then we swap the next number pointed by pointer $i$ with $nums[j]$, and move $i$ forward. Continue to traverse until $j$ reaches the end of the array, all non-zero elements of the array are moved to the front of the array in the original order, and all zero elements are moved to the end of the array. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/0300-0399/0389.Find the Difference/README.md b/solution/0300-0399/0389.Find the Difference/README.md index 8c527105f05d5..9da3653d797bf 100644 --- a/solution/0300-0399/0389.Find the Difference/README.md +++ b/solution/0300-0399/0389.Find the Difference/README.md @@ -45,17 +45,15 @@ **方法一:计数** -使用数组(`cnt`)统计 `s` 与 `t` 当中字符出现的次数:`s[i]` 进行 `cnt[s[i] - 'a']++`,`t[i]` 进行 `cnt[t[i] - 'a']--`。 +我们可以用一个哈希表或数组 $cnt$ 统计字符串 $s$ 中每个字符出现的次数,再遍历字符串 $t$,对于每个字符,我们在 $cnt$ 中减去一次出现的次数,如果对应次数为负数,则说明该字符在 $t$ 中出现的次数大于在 $s$ 中出现的次数,因此该字符为被添加的字符。 -完成统计后,找到符合 `cnt[i] == -1` 的 `i`,返回即可(`return 'a' + i`)。 - -时间复杂度 $O(n)$,空间复杂度 $O(C)$。本题中 $C=26$。 +时间复杂度 $O(n)$,空间复杂度 $O(|\Sigma|)$,其中 $n$ 为字符串的长度,而 $\Sigma$ 表示字符集,这里字符集为所有小写字母,所以 $|\Sigma|=26$。 **方法二:求和** -由于 `s` 与 `t` 只存在一个不同元素,可以统计两者所有字符 ASCII 码之和,再进行相减(`sum(t) - sum(s)`),即可得到 `t` 中那一个额外字符的 ASCII 码。 +我们可以将字符串 $t$ 中每个字符的 ASCII 码的值求和,再减去字符串 $s$ 中每个字符的 ASCII 码的值求和,最后的结果即为被添加的字符的 ASCII 码对应的值。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。 +时间复杂度 $O(n)$,其中 $n$ 为字符串的长度,空间复杂度 $O(1)$。 @@ -122,10 +120,15 @@ class Solution { class Solution { public: char findTheDifference(string s, string t) { - int cnt[26] = {0}; - for (char& c : s) ++cnt[c - 'a']; - for (char& c : t) - if (--cnt[c - 'a'] < 0) return c; + int cnt[26]{}; + for (char& c : s) { + ++cnt[c - 'a']; + } + for (char& c : t) { + if (--cnt[c - 'a'] < 0) { + return c; + } + } return ' '; } }; @@ -136,25 +139,64 @@ class Solution { public: char findTheDifference(string s, string t) { int a = 0, b = 0; - for (char& c : s) a += c; - for (char& c : t) b += c; + for (char& c : s) { + a += c; + } + for (char& c : t) { + b += c; + } return b - a; } }; ``` +### **Go** + +```go +func findTheDifference(s, t string) byte { + cnt := [26]int{} + for _, ch := range s { + cnt[ch-'a']++ + } + for i := 0; ; i++ { + ch := t[i] + cnt[ch-'a']-- + if cnt[ch-'a'] < 0 { + return ch + } + } +} +``` + +```go +func findTheDifference(s string, t string) byte { + ss := 0 + for _, c := range s { + ss -= int(c) + } + for _, c := range t { + ss += int(c) + } + return byte(ss) +} +``` + ### **TypeScript** ```ts function findTheDifference(s: string, t: string): string { - const n = s.length; - const count = new Array(26).fill(0); - for (let i = 0; i < n; i++) { - count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; - count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--; + const cnt: number[] = Array(26).fill(0); + for (const c of s) { + ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (const c of t) { + --cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (let i = 0; ; ++i) { + if (cnt[i] < 0) { + return String.fromCharCode(i + 'a'.charCodeAt(0)); + } } - count[t.charCodeAt(n) - 'a'.charCodeAt(0)]--; - return String.fromCharCode('a'.charCodeAt(0) + count.findIndex(v => v !== 0)); } ``` @@ -214,19 +256,17 @@ impl Solution { ```c char findTheDifference(char* s, char* t) { int n = strlen(s); - int count[26] = {0}; + int cnt[26] = {0}; for (int i = 0; i < n; i++) { - count[s[i] - 'a']++; - count[t[i] - 'a']--; + cnt[s[i] - 'a']++; + cnt[t[i] - 'a']--; } - count[t[n] - 'a']--; - int i; - for (i = 0; i < 26; i++) { - if (count[i]) { - break; + cnt[t[n] - 'a']--; + for (int i = 0;; i++) { + if (cnt[i]) { + return 'a' + i; } } - return 'a' + i; } ``` @@ -243,37 +283,6 @@ char findTheDifference(char* s, char* t) { } ``` -### **Go** - -```go -func findTheDifference(s, t string) byte { - cnt := [26]int{} - for _, ch := range s { - cnt[ch-'a']++ - } - for i := 0; ; i++ { - ch := t[i] - cnt[ch-'a']-- - if cnt[ch-'a'] < 0 { - return ch - } - } -} -``` - -```go -func findTheDifference(s string, t string) byte { - ss := 0 - for _, c := range s { - ss -= int(c) - } - for _, c := range t { - ss += int(c) - } - return byte(ss) -} -``` - ### **...** ``` diff --git a/solution/0300-0399/0389.Find the Difference/README_EN.md b/solution/0300-0399/0389.Find the Difference/README_EN.md index ff8812371017f..f2b1bbd0751f2 100644 --- a/solution/0300-0399/0389.Find the Difference/README_EN.md +++ b/solution/0300-0399/0389.Find the Difference/README_EN.md @@ -37,6 +37,18 @@ ## Solutions +**Solution 1: Counting** + +We can use a hash table or array $cnt$ to count the occurrence of each character in string $s$, then traverse string $t$. For each character, we subtract its occurrence in $cnt$. If the corresponding count is negative, it means that the occurrence of this character in $t$ is greater than in $s$, so this character is the added character. + +The time complexity is $O(n)$, and the space complexity is $O(|\Sigma|)$, where $n$ is the length of the string, and $\Sigma$ represents the character set. Here the character set is all lowercase letters, so $|\Sigma|=26$. + +**Solution 2: Summation** + +We can sum the ASCII values of each character in string $t$, then subtract the sum of the ASCII values of each character in string $s$. The final result is the ASCII value of the added character. + +The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$. + ### **Python3** @@ -98,10 +110,15 @@ class Solution { class Solution { public: char findTheDifference(string s, string t) { - int cnt[26] = {0}; - for (char& c : s) ++cnt[c - 'a']; - for (char& c : t) - if (--cnt[c - 'a'] < 0) return c; + int cnt[26]{}; + for (char& c : s) { + ++cnt[c - 'a']; + } + for (char& c : t) { + if (--cnt[c - 'a'] < 0) { + return c; + } + } return ' '; } }; @@ -112,25 +129,64 @@ class Solution { public: char findTheDifference(string s, string t) { int a = 0, b = 0; - for (char& c : s) a += c; - for (char& c : t) b += c; + for (char& c : s) { + a += c; + } + for (char& c : t) { + b += c; + } return b - a; } }; ``` +### **Go** + +```go +func findTheDifference(s, t string) byte { + cnt := [26]int{} + for _, ch := range s { + cnt[ch-'a']++ + } + for i := 0; ; i++ { + ch := t[i] + cnt[ch-'a']-- + if cnt[ch-'a'] < 0 { + return ch + } + } +} +``` + +```go +func findTheDifference(s string, t string) byte { + ss := 0 + for _, c := range s { + ss -= int(c) + } + for _, c := range t { + ss += int(c) + } + return byte(ss) +} +``` + ### **TypeScript** ```ts function findTheDifference(s: string, t: string): string { - const n = s.length; - const count = new Array(26).fill(0); - for (let i = 0; i < n; i++) { - count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; - count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--; + const cnt: number[] = Array(26).fill(0); + for (const c of s) { + ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (const c of t) { + --cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (let i = 0; ; ++i) { + if (cnt[i] < 0) { + return String.fromCharCode(i + 'a'.charCodeAt(0)); + } } - count[t.charCodeAt(n) - 'a'.charCodeAt(0)]--; - return String.fromCharCode('a'.charCodeAt(0) + count.findIndex(v => v !== 0)); } ``` @@ -190,19 +246,17 @@ impl Solution { ```c char findTheDifference(char* s, char* t) { int n = strlen(s); - int count[26] = {0}; + int cnt[26] = {0}; for (int i = 0; i < n; i++) { - count[s[i] - 'a']++; - count[t[i] - 'a']--; + cnt[s[i] - 'a']++; + cnt[t[i] - 'a']--; } - count[t[n] - 'a']--; - int i; - for (i = 0; i < 26; i++) { - if (count[i]) { - break; + cnt[t[n] - 'a']--; + for (int i = 0;; i++) { + if (cnt[i]) { + return 'a' + i; } } - return 'a' + i; } ``` @@ -219,37 +273,6 @@ char findTheDifference(char* s, char* t) { } ``` -### **Go** - -```go -func findTheDifference(s, t string) byte { - cnt := [26]int{} - for _, ch := range s { - cnt[ch-'a']++ - } - for i := 0; ; i++ { - ch := t[i] - cnt[ch-'a']-- - if cnt[ch-'a'] < 0 { - return ch - } - } -} -``` - -```go -func findTheDifference(s string, t string) byte { - ss := 0 - for _, c := range s { - ss -= int(c) - } - for _, c := range t { - ss += int(c) - } - return byte(ss) -} -``` - ### **...** ``` diff --git a/solution/0300-0399/0389.Find the Difference/Solution.cpp b/solution/0300-0399/0389.Find the Difference/Solution.cpp index 9b0717b437605..e0c3b8f7b9f99 100644 --- a/solution/0300-0399/0389.Find the Difference/Solution.cpp +++ b/solution/0300-0399/0389.Find the Difference/Solution.cpp @@ -1,10 +1,15 @@ -class Solution { -public: - char findTheDifference(string s, string t) { - int cnt[26] = {0}; - for (char& c : s) ++cnt[c - 'a']; - for (char& c : t) - if (--cnt[c - 'a'] < 0) return c; - return ' '; - } +class Solution { +public: + char findTheDifference(string s, string t) { + int cnt[26]{}; + for (char& c : s) { + ++cnt[c - 'a']; + } + for (char& c : t) { + if (--cnt[c - 'a'] < 0) { + return c; + } + } + return ' '; + } }; \ No newline at end of file diff --git a/solution/0300-0399/0389.Find the Difference/Solution.ts b/solution/0300-0399/0389.Find the Difference/Solution.ts index 38407053ac895..deb8507326a08 100644 --- a/solution/0300-0399/0389.Find the Difference/Solution.ts +++ b/solution/0300-0399/0389.Find the Difference/Solution.ts @@ -1,6 +1,14 @@ function findTheDifference(s: string, t: string): string { - return String.fromCharCode( - [...t].reduce((r, v) => r + v.charCodeAt(0), 0) - - [...s].reduce((r, v) => r + v.charCodeAt(0), 0), - ); + const cnt: number[] = Array(26).fill(0); + for (const c of s) { + ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (const c of t) { + --cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + for (let i = 0; ; ++i) { + if (cnt[i] < 0) { + return String.fromCharCode(i + 'a'.charCodeAt(0)); + } + } } diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README.md b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README.md index 6e24f921b47f9..e10decb24a56b 100644 --- a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README.md +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README.md @@ -47,6 +47,14 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 `arr` 的长度。 +**方法二:哈希表 + 数学** + +我们先找出数组 $arr$ 中的最小值 $a$ 和最大值 $b$,如果数组 $arr$ 可以重排成等差数列,那么公差 $d = \frac{b - a}{n - 1}$ 必须为整数。 + +我们可以用哈希表来记录数组 $arr$ 中的所有元素,然后遍历 $i \in [0, n)$,判断 $a + d \times i$ 是否在哈希表中,如果不在,说明数组 $arr$ 不能重排成等差数列,返回 `false`。否则遍历完数组后,返回 `true`。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `arr` 的长度。 + ### **Python3** @@ -61,6 +69,19 @@ class Solution: return all(b - a == d for a, b in pairwise(arr)) ``` +```python +class Solution: + def canMakeArithmeticProgression(self, arr: List[int]) -> bool: + a = min(arr) + b = max(arr) + n = len(arr) + if (b - a) % (n - 1): + return False + d = (b - a) // (n - 1) + s = set(arr) + return all(a + d * i in s for i in range(n)) +``` + ### **Java** @@ -80,6 +101,31 @@ class Solution { } ``` +```java +class Solution { + public boolean canMakeArithmeticProgression(int[] arr) { + int n = arr.length; + int a = arr[0], b = arr[0]; + Set s = new HashSet<>(); + for (int x : arr) { + a = Math.min(a, x); + b = Math.max(b, x); + s.add(x); + } + if ((b - a) % (n - 1) != 0) { + return false; + } + int d = (b - a) / (n - 1); + for (int i = 0; i < n; ++i) { + if (!s.contains(a + d * i)) { + return false; + } + } + return true; + } +} +``` + ### **C++** ```cpp @@ -98,6 +144,27 @@ public: }; ``` +```cpp +class Solution { +public: + bool canMakeArithmeticProgression(vector& arr) { + auto [a, b] = minmax_element(arr.begin(), arr.end()); + int n = arr.size(); + if ((*b - *a) % (n - 1) != 0) { + return false; + } + int d = (*b - *a) / (n - 1); + unordered_set s(arr.begin(), arr.end()); + for (int i = 0; i < n; ++i) { + if (!s.count(*a + d * i)) { + return false; + } + } + return true; + } +}; +``` + ### **Go** ```go @@ -113,6 +180,27 @@ func canMakeArithmeticProgression(arr []int) bool { } ``` +```go +func canMakeArithmeticProgression(arr []int) bool { + a, b := slices.Min(arr), slices.Max(arr) + n := len(arr) + if (b-a)%(n-1) != 0 { + return false + } + d := (b - a) / (n - 1) + s := map[int]bool{} + for _, x := range arr { + s[x] = true + } + for i := 0; i < n; i++ { + if !s[a+i*d] { + return false + } + } + return true +} +``` + ### **JavaScript** ```js @@ -123,7 +211,9 @@ func canMakeArithmeticProgression(arr []int) bool { var canMakeArithmeticProgression = function (arr) { arr.sort((a, b) => a - b); for (let i = 1; i < arr.length - 1; i++) { - if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) return false; + if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) { + return false; + } } return true; }; diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md index b658bd11922fc..e33adc443584a 100644 --- a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md @@ -35,6 +35,20 @@ ## Solutions +**Solution 1: Sorting + Traversal** + +We can first sort the array `arr`, then traverse the array, and check whether the difference between adjacent items is equal. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array `arr`. + +**Solution 2: Hash Table + Mathematics** + +We first find the minimum value $a$ and the maximum value $b$ in the array $arr$. If the array $arr$ can be rearranged into an arithmetic sequence, then the common difference $d = \frac{b - a}{n - 1}$ must be an integer. + +We can use a hash table to record all elements in the array $arr$, then traverse $i \in [0, n)$, and check whether $a + d \times i$ is in the hash table. If not, it means that the array $arr$ cannot be rearranged into an arithmetic sequence, and we return `false`. Otherwise, after traversing the array, we return `true`. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `arr`. + ### **Python3** @@ -47,6 +61,19 @@ class Solution: return all(b - a == d for a, b in pairwise(arr)) ``` +```python +class Solution: + def canMakeArithmeticProgression(self, arr: List[int]) -> bool: + a = min(arr) + b = max(arr) + n = len(arr) + if (b - a) % (n - 1): + return False + d = (b - a) // (n - 1) + s = set(arr) + return all(a + d * i in s for i in range(n)) +``` + ### **Java** ```java @@ -64,6 +91,31 @@ class Solution { } ``` +```java +class Solution { + public boolean canMakeArithmeticProgression(int[] arr) { + int n = arr.length; + int a = arr[0], b = arr[0]; + Set s = new HashSet<>(); + for (int x : arr) { + a = Math.min(a, x); + b = Math.max(b, x); + s.add(x); + } + if ((b - a) % (n - 1) != 0) { + return false; + } + int d = (b - a) / (n - 1); + for (int i = 0; i < n; ++i) { + if (!s.contains(a + d * i)) { + return false; + } + } + return true; + } +} +``` + ### **C++** ```cpp @@ -82,6 +134,27 @@ public: }; ``` +```cpp +class Solution { +public: + bool canMakeArithmeticProgression(vector& arr) { + auto [a, b] = minmax_element(arr.begin(), arr.end()); + int n = arr.size(); + if ((*b - *a) % (n - 1) != 0) { + return false; + } + int d = (*b - *a) / (n - 1); + unordered_set s(arr.begin(), arr.end()); + for (int i = 0; i < n; ++i) { + if (!s.count(*a + d * i)) { + return false; + } + } + return true; + } +}; +``` + ### **Go** ```go @@ -97,6 +170,27 @@ func canMakeArithmeticProgression(arr []int) bool { } ``` +```go +func canMakeArithmeticProgression(arr []int) bool { + a, b := slices.Min(arr), slices.Max(arr) + n := len(arr) + if (b-a)%(n-1) != 0 { + return false + } + d := (b - a) / (n - 1) + s := map[int]bool{} + for _, x := range arr { + s[x] = true + } + for i := 0; i < n; i++ { + if !s[a+i*d] { + return false + } + } + return true +} +``` + ### **JavaScript** ```js @@ -107,7 +201,9 @@ func canMakeArithmeticProgression(arr []int) bool { var canMakeArithmeticProgression = function (arr) { arr.sort((a, b) => a - b); for (let i = 1; i < arr.length - 1; i++) { - if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) return false; + if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) { + return false; + } } return true; }; diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution.js b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution.js index dce77eeeb943e..e63fbdd65a3b3 100644 --- a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution.js +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/Solution.js @@ -5,7 +5,9 @@ var canMakeArithmeticProgression = function (arr) { arr.sort((a, b) => a - b); for (let i = 1; i < arr.length - 1; i++) { - if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) return false; + if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) { + return false; + } } return true; }; diff --git a/solution/1700-1799/1768.Merge Strings Alternately/README.md b/solution/1700-1799/1768.Merge Strings Alternately/README.md index 08746f6b79660..410dce908a5e6 100644 --- a/solution/1700-1799/1768.Merge Strings Alternately/README.md +++ b/solution/1700-1799/1768.Merge Strings Alternately/README.md @@ -60,9 +60,9 @@ word2: p q **方法一:直接模拟** -遍历 `word1`, `word2` 两个字符串,依次取出字符,拼接到结果字符串中。Python 代码可以简化为一行。 +我们遍历 `word1`, `word2` 两个字符串,依次取出字符,拼接到结果字符串中。Python 代码可以简化为一行。 -时间复杂度 $O(m + n)$,忽略答案的空间消耗,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是两个字符串的长度。 +时间复杂度 $O(m + n)$,其中 $m$ 和 $n$ 分别是两个字符串的长度。忽略答案的空间消耗,空间复杂度 $O(1)$。 @@ -137,13 +137,17 @@ func mergeAlternately(word1 string, word2 string) string { ```ts function mergeAlternately(word1: string, word2: string): string { - const res = []; - const n = Math.max(word1.length, word2.length); - for (let i = 0; i < n; i++) { - word1[i] && res.push(word1[i]); - word2[i] && res.push(word2[i]); + const ans: string[] = []; + const [m, n] = [word1.length, word2.length]; + for (let i = 0; i < m || i < n; ++i) { + if (i < m) { + ans.push(word1[i]); + } + if (i < n) { + ans.push(word2[i]); + } } - return res.join(''); + return ans.join(''); } ``` diff --git a/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md b/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md index a482b8ee2b4ef..0dad35455e056 100644 --- a/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md +++ b/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md @@ -52,6 +52,12 @@ merged: a p b q c d ## Solutions +**Solution 1: Direct Simulation** + +We traverse the two strings `word1` and `word2`, take out the characters one by one, and append them to the result string. The Python code can be simplified into one line. + +The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two strings respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + ### **Python3** @@ -121,13 +127,17 @@ func mergeAlternately(word1 string, word2 string) string { ```ts function mergeAlternately(word1: string, word2: string): string { - const res = []; - const n = Math.max(word1.length, word2.length); - for (let i = 0; i < n; i++) { - word1[i] && res.push(word1[i]); - word2[i] && res.push(word2[i]); + const ans: string[] = []; + const [m, n] = [word1.length, word2.length]; + for (let i = 0; i < m || i < n; ++i) { + if (i < m) { + ans.push(word1[i]); + } + if (i < n) { + ans.push(word2[i]); + } } - return res.join(''); + return ans.join(''); } ``` diff --git a/solution/1700-1799/1768.Merge Strings Alternately/Solution.ts b/solution/1700-1799/1768.Merge Strings Alternately/Solution.ts index 5b53b7c8521c5..09b754d0b6d80 100644 --- a/solution/1700-1799/1768.Merge Strings Alternately/Solution.ts +++ b/solution/1700-1799/1768.Merge Strings Alternately/Solution.ts @@ -1,9 +1,13 @@ function mergeAlternately(word1: string, word2: string): string { - const res = []; - const n = Math.max(word1.length, word2.length); - for (let i = 0; i < n; i++) { - word1[i] && res.push(word1[i]); - word2[i] && res.push(word2[i]); + const ans: string[] = []; + const [m, n] = [word1.length, word2.length]; + for (let i = 0; i < m || i < n; ++i) { + if (i < m) { + ans.push(word1[i]); + } + if (i < n) { + ans.push(word2[i]); + } } - return res.join(''); + return ans.join(''); } diff --git a/solution/1800-1899/1822.Sign of the Product of an Array/README.md b/solution/1800-1899/1822.Sign of the Product of an Array/README.md index d311b07c6cae4..fed6be914fd8a 100644 --- a/solution/1800-1899/1822.Sign of the Product of an Array/README.md +++ b/solution/1800-1899/1822.Sign of the Product of an Array/README.md @@ -67,7 +67,7 @@ 遍历结束后,返回 `ans` 即可。 -时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。其中 $n$ 为数组长度。 +时间复杂度 $O(n)$,其中 $n$ 为数组长度。空间复杂度 $O(1)$。 diff --git a/solution/1800-1899/1822.Sign of the Product of an Array/README_EN.md b/solution/1800-1899/1822.Sign of the Product of an Array/README_EN.md index 9988ff211d889..fe1a5a0513497 100644 --- a/solution/1800-1899/1822.Sign of the Product of an Array/README_EN.md +++ b/solution/1800-1899/1822.Sign of the Product of an Array/README_EN.md @@ -51,6 +51,18 @@ ## Solutions +**Solution 1: Direct Traversal** + +The problem requires us to return the sign of the product of the array elements, i.e., return $1$ for positive numbers, $-1$ for negative numbers, and $0$ if it equals $0$. + +We can define an answer variable `ans`, initially set to $1$. + +Then we traverse each element $v$ in the array. If $v$ is a negative number, we multiply `ans` by $-1$. If $v$ is $0$, we return $0$ in advance. + +After the traversal is over, we return `ans`. + +The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. + ### **Python3**