diff --git a/images/starcharts.svg b/images/starcharts.svg
index 001fe576b4350..940d85895c980 100644
--- a/images/starcharts.svg
+++ b/images/starcharts.svg
@@ -1,4 +1,4 @@
-
+
\ No newline at end of file
+L 948 18
+L 948 18
+L 948 18
+L 948 18
+L 948 18
+L 948 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 949 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18
+L 950 18" style="stroke-width:2;stroke:rgba(129,199,239,1.0);fill:none"/>
\ No newline at end of file
diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md
index 8e86fae398f1d..6ea9e375205e8 100644
--- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md
+++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md
@@ -65,7 +65,7 @@
最后我们返回答案即可。
-时间复杂度为 $O(n^2)$,其中 $n$ 是字符串 $s$ 的长度。
+时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$,其中 $n$ 为字符串 $s$ 的长度。
@@ -82,11 +82,11 @@ class Solution:
for i in range(n):
f[i][i] = 1
ans = 0
- for i in range(n - 1, -1, -1):
+ for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i + 1][j - 1] + 2
- if i < len(word1) and j >= len(word1):
+ if i < len(word1) <= j:
ans = max(ans, f[i][j])
else:
f[i][j] = max(f[i + 1][j], f[i][j - 1])
@@ -180,6 +180,62 @@ func longestPalindrome(word1 string, word2 string) (ans int) {
}
```
+### **TypeScript**
+
+```ts
+function longestPalindrome(word1: string, word2: string): number {
+ const s = word1 + word2;
+ const n = s.length;
+ const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0));
+ for (let i = 0; i < n; ++i) {
+ f[i][i] = 1;
+ }
+ let ans = 0;
+ for (let i = n - 2; ~i; --i) {
+ for (let j = i + 1; j < n; ++j) {
+ if (s[i] === s[j]) {
+ f[i][j] = f[i + 1][j - 1] + 2;
+ if (i < word1.length && j >= word1.length) {
+ ans = Math.max(ans, f[i][j]);
+ }
+ } else {
+ f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]);
+ }
+ }
+ }
+ return ans;
+}
+```
+
+### **Rust**
+
+```rust
+impl Solution {
+ pub fn longest_palindrome(word1: String, word2: String) -> i32 {
+ let s: Vec = format!("{}{}", word1, word2).chars().collect();
+ let n = s.len();
+ let mut f = vec![vec![0; n]; n];
+ for i in 0..n {
+ f[i][i] = 1;
+ }
+ let mut ans = 0;
+ for i in (0..n - 1).rev() {
+ for j in i + 1..n {
+ if s[i] == s[j] {
+ f[i][j] = f[i + 1][j - 1] + 2;
+ if i < word1.len() && j >= word1.len() {
+ ans = ans.max(f[i][j]);
+ }
+ } else {
+ f[i][j] = f[i + 1][j].max(f[i][j - 1]);
+ }
+ }
+ }
+ ans
+ }
+}
+```
+
### **...**
```
diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md
index c9e25ab9b7887..729f1e7db4d42 100644
--- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md
+++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md
@@ -50,6 +50,20 @@
## Solutions
+**Solution 1: Dynamic Programming**
+
+First, we concatenate strings `word1` and `word2` to get string $s$. Then we can transform the problem into finding the length of the longest palindromic subsequence in string $s$. However, when calculating the final answer, we need to ensure that at least one character in the palindrome string comes from `word1` and another character comes from `word2`.
+
+We define $f[i][j]$ as the length of the longest palindromic subsequence in the substring of string $s$ with index range $[i, j]$.
+
+If $s[i] = s[j]$, then $s[i]$ and $s[j]$ must be in the longest palindromic subsequence, at this time $f[i][j] = f[i + 1][j - 1] + 2$. At this point, we also need to judge whether $s[i]$ and $s[j]$ come from `word1` and `word2`. If so, we update the maximum value of the answer to $ans=\max(ans, f[i][j])$.
+
+If $s[i] \neq s[j]$, then $s[i]$ and $s[j]$ will definitely not appear in the longest palindromic subsequence at the same time, at this time $f[i][j] = max(f[i + 1][j], f[i][j - 1])$.
+
+Finally, we return the answer.
+
+The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of string $s$.
+
### **Python3**
@@ -63,11 +77,11 @@ class Solution:
for i in range(n):
f[i][i] = 1
ans = 0
- for i in range(n - 1, -1, -1):
+ for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i + 1][j - 1] + 2
- if i < len(word1) and j >= len(word1):
+ if i < len(word1) <= j:
ans = max(ans, f[i][j])
else:
f[i][j] = max(f[i + 1][j], f[i][j - 1])
@@ -159,6 +173,62 @@ func longestPalindrome(word1 string, word2 string) (ans int) {
}
```
+### **TypeScript**
+
+```ts
+function longestPalindrome(word1: string, word2: string): number {
+ const s = word1 + word2;
+ const n = s.length;
+ const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0));
+ for (let i = 0; i < n; ++i) {
+ f[i][i] = 1;
+ }
+ let ans = 0;
+ for (let i = n - 2; ~i; --i) {
+ for (let j = i + 1; j < n; ++j) {
+ if (s[i] === s[j]) {
+ f[i][j] = f[i + 1][j - 1] + 2;
+ if (i < word1.length && j >= word1.length) {
+ ans = Math.max(ans, f[i][j]);
+ }
+ } else {
+ f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]);
+ }
+ }
+ }
+ return ans;
+}
+```
+
+### **Rust**
+
+```rust
+impl Solution {
+ pub fn longest_palindrome(word1: String, word2: String) -> i32 {
+ let s: Vec = format!("{}{}", word1, word2).chars().collect();
+ let n = s.len();
+ let mut f = vec![vec![0; n]; n];
+ for i in 0..n {
+ f[i][i] = 1;
+ }
+ let mut ans = 0;
+ for i in (0..n - 1).rev() {
+ for j in i + 1..n {
+ if s[i] == s[j] {
+ f[i][j] = f[i + 1][j - 1] + 2;
+ if i < word1.len() && j >= word1.len() {
+ ans = ans.max(f[i][j]);
+ }
+ } else {
+ f[i][j] = f[i + 1][j].max(f[i][j - 1]);
+ }
+ }
+ }
+ ans
+ }
+}
+```
+
### **...**
```
diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py
index 4d9d9060c4de1..9980153e69e14 100644
--- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py
+++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py
@@ -1,17 +1,17 @@
-class Solution:
- def longestPalindrome(self, word1: str, word2: str) -> int:
- s = word1 + word2
- n = len(s)
- f = [[0] * n for _ in range(n)]
- for i in range(n):
- f[i][i] = 1
- ans = 0
- for i in range(n - 1, -1, -1):
- for j in range(i + 1, n):
- if s[i] == s[j]:
- f[i][j] = f[i + 1][j - 1] + 2
- if i < len(word1) and j >= len(word1):
- ans = max(ans, f[i][j])
- else:
- f[i][j] = max(f[i + 1][j], f[i][j - 1])
- return ans
+class Solution:
+ def longestPalindrome(self, word1: str, word2: str) -> int:
+ s = word1 + word2
+ n = len(s)
+ f = [[0] * n for _ in range(n)]
+ for i in range(n):
+ f[i][i] = 1
+ ans = 0
+ for i in range(n - 2, -1, -1):
+ for j in range(i + 1, n):
+ if s[i] == s[j]:
+ f[i][j] = f[i + 1][j - 1] + 2
+ if i < len(word1) <= j:
+ ans = max(ans, f[i][j])
+ else:
+ f[i][j] = max(f[i + 1][j], f[i][j - 1])
+ return ans
diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.rs b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.rs
new file mode 100644
index 0000000000000..2e4b9ac26d36b
--- /dev/null
+++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.rs
@@ -0,0 +1,24 @@
+impl Solution {
+ pub fn longest_palindrome(word1: String, word2: String) -> i32 {
+ let s: Vec = format!("{}{}", word1, word2).chars().collect();
+ let n = s.len();
+ let mut f = vec![vec![0; n]; n];
+ for i in 0..n {
+ f[i][i] = 1;
+ }
+ let mut ans = 0;
+ for i in (0..n - 1).rev() {
+ for j in i + 1..n {
+ if s[i] == s[j] {
+ f[i][j] = f[i + 1][j - 1] + 2;
+ if i < word1.len() && j >= word1.len() {
+ ans = ans.max(f[i][j]);
+ }
+ } else {
+ f[i][j] = f[i + 1][j].max(f[i][j - 1]);
+ }
+ }
+ }
+ ans
+ }
+}
diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.ts b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.ts
new file mode 100644
index 0000000000000..161819205ea0e
--- /dev/null
+++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.ts
@@ -0,0 +1,22 @@
+function longestPalindrome(word1: string, word2: string): number {
+ const s = word1 + word2;
+ const n = s.length;
+ const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0));
+ for (let i = 0; i < n; ++i) {
+ f[i][i] = 1;
+ }
+ let ans = 0;
+ for (let i = n - 2; ~i; --i) {
+ for (let j = i + 1; j < n; ++j) {
+ if (s[i] === s[j]) {
+ f[i][j] = f[i + 1][j - 1] + 2;
+ if (i < word1.length && j >= word1.length) {
+ ans = Math.max(ans, f[i][j]);
+ }
+ } else {
+ f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]);
+ }
+ }
+ }
+ return ans;
+}
diff --git a/solution/1700-1799/1772.Sort Features by Popularity/README.md b/solution/1700-1799/1772.Sort Features by Popularity/README.md
index 70479184f63b4..762b662cc1fd7 100644
--- a/solution/1700-1799/1772.Sort Features by Popularity/README.md
+++ b/solution/1700-1799/1772.Sort Features by Popularity/README.md
@@ -51,7 +51,7 @@
**方法一:哈希表 + 自定义排序**
-我们遍历 `responses`,对于 `responses[i]` 中的每个单词,我们用一个哈希表 `ws` 暂存。接下来将 `ws` 中的单词记录到哈希表 `cnt` 中,记录每个单词出现的次数。
+我们遍历 `responses`,对于 `responses[i]` 中的每个单词,我们用一个哈希表 `vis` 暂存。接下来将 `vis` 中的单词记录到哈希表 `cnt` 中,记录每个单词出现的次数。
接下来,采用自定义排序,将 `features` 中的单词按照出现次数从大到小排序,如果出现次数相同,则按照出现的下标从小到大排序。
@@ -67,11 +67,10 @@
class Solution:
def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]:
cnt = Counter()
- for r in responses:
- ws = set(r.split())
- for s in ws:
- cnt[s] += 1
- return sorted(features, key=lambda x: -cnt[x])
+ for s in responses:
+ for w in set(s.split()):
+ cnt[w] += 1
+ return sorted(features, key=lambda w: -cnt[w])
```
### **Java**
@@ -82,26 +81,26 @@ class Solution:
class Solution {
public String[] sortFeatures(String[] features, String[] responses) {
Map cnt = new HashMap<>();
- for (String r : responses) {
- Set ws = new HashSet<>();
- for (String w : r.split(" ")) {
- ws.add(w);
- }
- for (String w : ws) {
- cnt.put(w, cnt.getOrDefault(w, 0) + 1);
+ for (String s : responses) {
+ Set vis = new HashSet<>();
+ for (String w : s.split(" ")) {
+ if (vis.add(w)) {
+ cnt.merge(w, 1, Integer::sum);
+ }
}
}
int n = features.length;
Integer[] idx = new Integer[n];
- for (int i = 0; i < n; ++i) {
+ for (int i = 0; i < n; i++) {
idx[i] = i;
}
Arrays.sort(idx, (i, j) -> {
- int d = cnt.getOrDefault(features[j], 0) - cnt.getOrDefault(features[i], 0);
- return d == 0 ? i - j : d;
+ int x = cnt.getOrDefault(features[i], 0);
+ int y = cnt.getOrDefault(features[j], 0);
+ return x == y ? i - j : y - x;
});
String[] ans = new String[n];
- for (int i = 0; i < n; ++i) {
+ for (int i = 0; i < n; i++) {
ans[i] = features[idx[i]];
}
return ans;
@@ -116,23 +115,23 @@ class Solution {
public:
vector sortFeatures(vector& features, vector& responses) {
unordered_map cnt;
- for (auto& r : responses) {
- stringstream ss(r);
- string t;
- unordered_set ws;
- while (ss >> t) {
- ws.insert(t);
+ for (auto& s : responses) {
+ istringstream iss(s);
+ string w;
+ unordered_set st;
+ while (iss >> w) {
+ st.insert(w);
}
- for (auto& w : ws) {
- cnt[w]++;
+ for (auto& w : st) {
+ ++cnt[w];
}
}
int n = features.size();
vector idx(n);
iota(idx.begin(), idx.end(), 0);
- sort(idx.begin(), idx.end(), [&](int i, int j) -> bool {
- int d = cnt[features[i]] - cnt[features[j]];
- return d > 0 || (d == 0 && i < j);
+ sort(idx.begin(), idx.end(), [&](int i, int j) {
+ int x = cnt[features[i]], y = cnt[features[j]];
+ return x == y ? i < j : x > y;
});
vector ans(n);
for (int i = 0; i < n; ++i) {
@@ -148,29 +147,43 @@ public:
```go
func sortFeatures(features []string, responses []string) []string {
cnt := map[string]int{}
- for _, r := range responses {
- ws := map[string]bool{}
- for _, s := range strings.Split(r, " ") {
- ws[s] = true
- }
- for w := range ws {
- cnt[w]++
+ for _, s := range responses {
+ vis := map[string]bool{}
+ for _, w := range strings.Split(s, " ") {
+ if !vis[w] {
+ cnt[w]++
+ vis[w] = true
+ }
}
}
- n := len(features)
- idx := make([]int, n)
- for i := range idx {
- idx[i] = i
- }
- sort.Slice(idx, func(i, j int) bool {
- d := cnt[features[idx[i]]] - cnt[features[idx[j]]]
- return d > 0 || (d == 0 && idx[i] < idx[j])
- })
- ans := make([]string, n)
- for i := range ans {
- ans[i] = features[idx[i]]
- }
- return ans
+ sort.SliceStable(features, func(i, j int) bool { return cnt[features[i]] > cnt[features[j]] })
+ return features
+}
+```
+
+### **TypeScript**
+
+```ts
+function sortFeatures(features: string[], responses: string[]): string[] {
+ const cnt: Map = new Map();
+ for (const s of responses) {
+ const vis: Set = new Set();
+ for (const w of s.split(' ')) {
+ if (vis.has(w)) {
+ continue;
+ }
+ vis.add(w);
+ cnt.set(w, (cnt.get(w) || 0) + 1);
+ }
+ }
+ const n = features.length;
+ const idx: number[] = Array.from({ length: n }, (_, i) => i);
+ idx.sort((i, j) => {
+ const x = cnt.get(features[i]) || 0;
+ const y = cnt.get(features[j]) || 0;
+ return x === y ? i - j : y - x;
+ });
+ return idx.map(i => features[i]);
}
```
diff --git a/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md b/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md
index fa61ea0f4914a..d8849be99f6b0 100644
--- a/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md
+++ b/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md
@@ -43,6 +43,14 @@
## Solutions
+**Solution 1: Hash Table + Custom Sorting**
+
+We traverse `responses`, and for each word in `responses[i]`, we temporarily store it in a hash table `vis`. Next, we record the words in `vis` into the hash table `cnt`, recording the number of times each word appears.
+
+Next, we use custom sorting to sort the words in `features` in descending order of occurrence. If the number of occurrences is the same, we sort them in ascending order of the index where they appear.
+
+The time complexity is $O(n \times \log n)$, where $n$ is the length of `features`.
+
### **Python3**
@@ -51,11 +59,10 @@
class Solution:
def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]:
cnt = Counter()
- for r in responses:
- ws = set(r.split())
- for s in ws:
- cnt[s] += 1
- return sorted(features, key=lambda x: -cnt[x])
+ for s in responses:
+ for w in set(s.split()):
+ cnt[w] += 1
+ return sorted(features, key=lambda w: -cnt[w])
```
### **Java**
@@ -64,26 +71,26 @@ class Solution:
class Solution {
public String[] sortFeatures(String[] features, String[] responses) {
Map cnt = new HashMap<>();
- for (String r : responses) {
- Set ws = new HashSet<>();
- for (String w : r.split(" ")) {
- ws.add(w);
- }
- for (String w : ws) {
- cnt.put(w, cnt.getOrDefault(w, 0) + 1);
+ for (String s : responses) {
+ Set vis = new HashSet<>();
+ for (String w : s.split(" ")) {
+ if (vis.add(w)) {
+ cnt.merge(w, 1, Integer::sum);
+ }
}
}
int n = features.length;
Integer[] idx = new Integer[n];
- for (int i = 0; i < n; ++i) {
+ for (int i = 0; i < n; i++) {
idx[i] = i;
}
Arrays.sort(idx, (i, j) -> {
- int d = cnt.getOrDefault(features[j], 0) - cnt.getOrDefault(features[i], 0);
- return d == 0 ? i - j : d;
+ int x = cnt.getOrDefault(features[i], 0);
+ int y = cnt.getOrDefault(features[j], 0);
+ return x == y ? i - j : y - x;
});
String[] ans = new String[n];
- for (int i = 0; i < n; ++i) {
+ for (int i = 0; i < n; i++) {
ans[i] = features[idx[i]];
}
return ans;
@@ -98,23 +105,23 @@ class Solution {
public:
vector sortFeatures(vector& features, vector& responses) {
unordered_map cnt;
- for (auto& r : responses) {
- stringstream ss(r);
- string t;
- unordered_set ws;
- while (ss >> t) {
- ws.insert(t);
+ for (auto& s : responses) {
+ istringstream iss(s);
+ string w;
+ unordered_set st;
+ while (iss >> w) {
+ st.insert(w);
}
- for (auto& w : ws) {
- cnt[w]++;
+ for (auto& w : st) {
+ ++cnt[w];
}
}
int n = features.size();
vector idx(n);
iota(idx.begin(), idx.end(), 0);
- sort(idx.begin(), idx.end(), [&](int i, int j) -> bool {
- int d = cnt[features[i]] - cnt[features[j]];
- return d > 0 || (d == 0 && i < j);
+ sort(idx.begin(), idx.end(), [&](int i, int j) {
+ int x = cnt[features[i]], y = cnt[features[j]];
+ return x == y ? i < j : x > y;
});
vector ans(n);
for (int i = 0; i < n; ++i) {
@@ -130,29 +137,43 @@ public:
```go
func sortFeatures(features []string, responses []string) []string {
cnt := map[string]int{}
- for _, r := range responses {
- ws := map[string]bool{}
- for _, s := range strings.Split(r, " ") {
- ws[s] = true
+ for _, s := range responses {
+ vis := map[string]bool{}
+ for _, w := range strings.Split(s, " ") {
+ if !vis[w] {
+ cnt[w]++
+ vis[w] = true
+ }
}
- for w := range ws {
- cnt[w]++
- }
- }
- n := len(features)
- idx := make([]int, n)
- for i := range idx {
- idx[i] = i
}
- sort.Slice(idx, func(i, j int) bool {
- d := cnt[features[idx[i]]] - cnt[features[idx[j]]]
- return d > 0 || (d == 0 && idx[i] < idx[j])
- })
- ans := make([]string, n)
- for i := range ans {
- ans[i] = features[idx[i]]
- }
- return ans
+ sort.SliceStable(features, func(i, j int) bool { return cnt[features[i]] > cnt[features[j]] })
+ return features
+}
+```
+
+### **TypeScript**
+
+```ts
+function sortFeatures(features: string[], responses: string[]): string[] {
+ const cnt: Map = new Map();
+ for (const s of responses) {
+ const vis: Set = new Set();
+ for (const w of s.split(' ')) {
+ if (vis.has(w)) {
+ continue;
+ }
+ vis.add(w);
+ cnt.set(w, (cnt.get(w) || 0) + 1);
+ }
+ }
+ const n = features.length;
+ const idx: number[] = Array.from({ length: n }, (_, i) => i);
+ idx.sort((i, j) => {
+ const x = cnt.get(features[i]) || 0;
+ const y = cnt.get(features[j]) || 0;
+ return x === y ? i - j : y - x;
+ });
+ return idx.map(i => features[i]);
}
```
diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp b/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp
index 18bb88ca04f5a..dba4a4c39152e 100644
--- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp
+++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp
@@ -1,29 +1,29 @@
-class Solution {
-public:
- vector sortFeatures(vector& features, vector& responses) {
- unordered_map cnt;
- for (auto& r : responses) {
- stringstream ss(r);
- string t;
- unordered_set ws;
- while (ss >> t) {
- ws.insert(t);
- }
- for (auto& w : ws) {
- cnt[w]++;
- }
- }
- int n = features.size();
- vector idx(n);
- iota(idx.begin(), idx.end(), 0);
- sort(idx.begin(), idx.end(), [&](int i, int j) -> bool {
- int d = cnt[features[i]] - cnt[features[j]];
- return d > 0 || (d == 0 && i < j);
- });
- vector ans(n);
- for (int i = 0; i < n; ++i) {
- ans[i] = features[idx[i]];
- }
- return ans;
- }
+class Solution {
+public:
+ vector sortFeatures(vector& features, vector& responses) {
+ unordered_map cnt;
+ for (auto& s : responses) {
+ istringstream iss(s);
+ string w;
+ unordered_set st;
+ while (iss >> w) {
+ st.insert(w);
+ }
+ for (auto& w : st) {
+ ++cnt[w];
+ }
+ }
+ int n = features.size();
+ vector idx(n);
+ iota(idx.begin(), idx.end(), 0);
+ sort(idx.begin(), idx.end(), [&](int i, int j) {
+ int x = cnt[features[i]], y = cnt[features[j]];
+ return x == y ? i < j : x > y;
+ });
+ vector ans(n);
+ for (int i = 0; i < n; ++i) {
+ ans[i] = features[idx[i]];
+ }
+ return ans;
+ }
};
\ No newline at end of file
diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.go b/solution/1700-1799/1772.Sort Features by Popularity/Solution.go
index d17126fc85a43..5e0504ca80658 100644
--- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.go
+++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.go
@@ -1,26 +1,14 @@
func sortFeatures(features []string, responses []string) []string {
cnt := map[string]int{}
- for _, r := range responses {
- ws := map[string]bool{}
- for _, s := range strings.Split(r, " ") {
- ws[s] = true
+ for _, s := range responses {
+ vis := map[string]bool{}
+ for _, w := range strings.Split(s, " ") {
+ if !vis[w] {
+ cnt[w]++
+ vis[w] = true
+ }
}
- for w := range ws {
- cnt[w]++
- }
- }
- n := len(features)
- idx := make([]int, n)
- for i := range idx {
- idx[i] = i
- }
- sort.Slice(idx, func(i, j int) bool {
- d := cnt[features[idx[i]]] - cnt[features[idx[j]]]
- return d > 0 || (d == 0 && idx[i] < idx[j])
- })
- ans := make([]string, n)
- for i := range ans {
- ans[i] = features[idx[i]]
}
- return ans
+ sort.SliceStable(features, func(i, j int) bool { return cnt[features[i]] > cnt[features[j]] })
+ return features
}
\ No newline at end of file
diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.java b/solution/1700-1799/1772.Sort Features by Popularity/Solution.java
index cbb1d31ac3c3c..702a7979d845f 100644
--- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.java
+++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.java
@@ -1,28 +1,28 @@
-class Solution {
- public String[] sortFeatures(String[] features, String[] responses) {
- Map cnt = new HashMap<>();
- for (String r : responses) {
- Set ws = new HashSet<>();
- for (String w : r.split(" ")) {
- ws.add(w);
- }
- for (String w : ws) {
- cnt.put(w, cnt.getOrDefault(w, 0) + 1);
- }
- }
- int n = features.length;
- Integer[] idx = new Integer[n];
- for (int i = 0; i < n; ++i) {
- idx[i] = i;
- }
- Arrays.sort(idx, (i, j) -> {
- int d = cnt.getOrDefault(features[j], 0) - cnt.getOrDefault(features[i], 0);
- return d == 0 ? i - j : d;
- });
- String[] ans = new String[n];
- for (int i = 0; i < n; ++i) {
- ans[i] = features[idx[i]];
- }
- return ans;
- }
+class Solution {
+ public String[] sortFeatures(String[] features, String[] responses) {
+ Map cnt = new HashMap<>();
+ for (String s : responses) {
+ Set vis = new HashSet<>();
+ for (String w : s.split(" ")) {
+ if (vis.add(w)) {
+ cnt.merge(w, 1, Integer::sum);
+ }
+ }
+ }
+ int n = features.length;
+ Integer[] idx = new Integer[n];
+ for (int i = 0; i < n; i++) {
+ idx[i] = i;
+ }
+ Arrays.sort(idx, (i, j) -> {
+ int x = cnt.getOrDefault(features[i], 0);
+ int y = cnt.getOrDefault(features[j], 0);
+ return x == y ? i - j : y - x;
+ });
+ String[] ans = new String[n];
+ for (int i = 0; i < n; i++) {
+ ans[i] = features[idx[i]];
+ }
+ return ans;
+ }
}
\ No newline at end of file
diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.py b/solution/1700-1799/1772.Sort Features by Popularity/Solution.py
index f2bd217e047a8..5250bc917eb10 100644
--- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.py
+++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.py
@@ -1,8 +1,7 @@
-class Solution:
- def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]:
- cnt = Counter()
- for r in responses:
- ws = set(r.split())
- for s in ws:
- cnt[s] += 1
- return sorted(features, key=lambda x: -cnt[x])
+class Solution:
+ def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]:
+ cnt = Counter()
+ for s in responses:
+ for w in set(s.split()):
+ cnt[w] += 1
+ return sorted(features, key=lambda w: -cnt[w])
diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.ts b/solution/1700-1799/1772.Sort Features by Popularity/Solution.ts
new file mode 100644
index 0000000000000..1a6ac9ce17b54
--- /dev/null
+++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.ts
@@ -0,0 +1,21 @@
+function sortFeatures(features: string[], responses: string[]): string[] {
+ const cnt: Map = new Map();
+ for (const s of responses) {
+ const vis: Set = new Set();
+ for (const w of s.split(' ')) {
+ if (vis.has(w)) {
+ continue;
+ }
+ vis.add(w);
+ cnt.set(w, (cnt.get(w) || 0) + 1);
+ }
+ }
+ const n = features.length;
+ const idx: number[] = Array.from({ length: n }, (_, i) => i);
+ idx.sort((i, j) => {
+ const x = cnt.get(features[i]) || 0;
+ const y = cnt.get(features[j]) || 0;
+ return x === y ? i - j : y - x;
+ });
+ return idx.map(i => features[i]);
+}
diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/README.md b/solution/1700-1799/1781.Sum of Beauty of All Substrings/README.md
index 77e194d77ee6c..c0257d3ab4de6 100644
--- a/solution/1700-1799/1781.Sum of Beauty of All Substrings/README.md
+++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/README.md
@@ -67,6 +67,30 @@ class Solution:
return ans
```
+```python
+class Solution:
+ def beautySum(self, s: str) -> int:
+ ans, n = 0, len(s)
+ for i in range(n):
+ cnt = Counter()
+ freq = Counter()
+ mi = mx = 1
+ for j in range(i, n):
+ freq[cnt[s[j]]] -= 1
+ cnt[s[j]] += 1
+ freq[cnt[s[j]]] += 1
+
+ if cnt[s[j]] == 1:
+ mi = 1
+ if freq[mi] == 0:
+ mi += 1
+ if cnt[s[j]] > mx:
+ mx = cnt[s[j]]
+
+ ans += mx - mi
+ return ans
+```
+
### **Java**
@@ -95,6 +119,38 @@ class Solution {
}
```
+```java
+class Solution {
+ public int beautySum(String s) {
+ int n = s.length();
+ int ans = 0;
+ for (int i = 0; i < n; ++i) {
+ int[] cnt = new int[26];
+ Map freq = new HashMap<>();
+ int mi = 1, mx = 1;
+ for (int j = i; j < n; ++j) {
+ int k = s.charAt(j) - 'a';
+ freq.merge(cnt[k], -1, Integer::sum);
+ ++cnt[k];
+ freq.merge(cnt[k], 1, Integer::sum);
+
+ if (cnt[k] == 1) {
+ mi = 1;
+ }
+ if (freq.getOrDefault(mi, 0) == 0) {
+ ++mi;
+ }
+ if (cnt[k] > mx) {
+ mx = cnt[k];
+ }
+ ans += mx - mi;
+ }
+ }
+ return ans;
+ }
+}
+```
+
### **C++**
```cpp
@@ -123,6 +179,39 @@ public:
};
```
+```cpp
+class Solution {
+public:
+ int beautySum(string s) {
+ int n = s.size();
+ int ans = 0;
+ for (int i = 0; i < n; ++i) {
+ int cnt[26]{};
+ unordered_map freq;
+ int mi = 1, mx = 1;
+ for (int j = i; j < n; ++j) {
+ int k = s[j] - 'a';
+ --freq[cnt[k]];
+ ++cnt[k];
+ ++freq[cnt[k]];
+
+ if (cnt[k] == 1) {
+ mi = 1;
+ }
+ if (freq[mi] == 0) {
+ ++mi;
+ }
+ if (cnt[k] > mx) {
+ mx = cnt[k];
+ }
+ ans += mx - mi;
+ }
+ }
+ return ans;
+ }
+};
+```
+
### **Go**
```go
@@ -149,6 +238,35 @@ func beautySum(s string) (ans int) {
}
```
+```go
+func beautySum(s string) (ans int) {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ cnt := [26]int{}
+ freq := map[int]int{}
+ mi, mx := 1, 1
+ for j := i; j < n; j++ {
+ k := int(s[j] - 'a')
+ freq[cnt[k]]--
+ cnt[k]++
+ freq[cnt[k]]++
+
+ if cnt[k] == 1 {
+ mi = 1
+ }
+ if freq[mi] == 0 {
+ mi++
+ }
+ if cnt[k] > mx {
+ mx = cnt[k]
+ }
+ ans += mx - mi
+ }
+ }
+ return
+}
+```
+
### **JavaScript**
```js
@@ -170,6 +288,39 @@ var beautySum = function (s) {
};
```
+```js
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var beautySum = function (s) {
+ const n = s.length;
+ let ans = 0;
+ for (let i = 0; i < n; ++i) {
+ const cnt = Array(26).fill(0);
+ const freq = new Map();
+ let [mi, mx] = [1, 1];
+ for (let j = i; j < n; ++j) {
+ const k = s[j].charCodeAt() - 97;
+ freq.set(cnt[k], (freq.get(cnt[k]) || 0) - 1);
+ ++cnt[k];
+ freq.set(cnt[k], (freq.get(cnt[k]) || 0) + 1);
+ if (cnt[k] === 1) {
+ mi = 1;
+ }
+ if (freq.get(mi) === 0) {
+ ++mi;
+ }
+ if (cnt[k] > mx) {
+ mx = cnt[k];
+ }
+ ans += mx - mi;
+ }
+ }
+ return ans;
+};
+```
+
### **...**
```
diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md b/solution/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md
index b08ad5d5d76d6..307f99dcf51c4 100644
--- a/solution/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md
+++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md
@@ -37,6 +37,12 @@
## Solutions
+**Solution 1: Enumeration + Counting**
+
+Enumerate the starting position $i$ of each substring, find all substrings with the character at this starting position as the left endpoint, then calculate the beauty value of each substring, and accumulate it to the answer.
+
+The time complexity is $O(n^2 \times C)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string, and $C$ is the size of the character set. In this problem, $C = 26$.
+
### **Python3**
@@ -53,6 +59,30 @@ class Solution:
return ans
```
+```python
+class Solution:
+ def beautySum(self, s: str) -> int:
+ ans, n = 0, len(s)
+ for i in range(n):
+ cnt = Counter()
+ freq = Counter()
+ mi = mx = 1
+ for j in range(i, n):
+ freq[cnt[s[j]]] -= 1
+ cnt[s[j]] += 1
+ freq[cnt[s[j]]] += 1
+
+ if cnt[s[j]] == 1:
+ mi = 1
+ if freq[mi] == 0:
+ mi += 1
+ if cnt[s[j]] > mx:
+ mx = cnt[s[j]]
+
+ ans += mx - mi
+ return ans
+```
+
### **Java**
```java
@@ -79,6 +109,38 @@ class Solution {
}
```
+```java
+class Solution {
+ public int beautySum(String s) {
+ int n = s.length();
+ int ans = 0;
+ for (int i = 0; i < n; ++i) {
+ int[] cnt = new int[26];
+ Map freq = new HashMap<>();
+ int mi = 1, mx = 1;
+ for (int j = i; j < n; ++j) {
+ int k = s.charAt(j) - 'a';
+ freq.merge(cnt[k], -1, Integer::sum);
+ ++cnt[k];
+ freq.merge(cnt[k], 1, Integer::sum);
+
+ if (cnt[k] == 1) {
+ mi = 1;
+ }
+ if (freq.getOrDefault(mi, 0) == 0) {
+ ++mi;
+ }
+ if (cnt[k] > mx) {
+ mx = cnt[k];
+ }
+ ans += mx - mi;
+ }
+ }
+ return ans;
+ }
+}
+```
+
### **C++**
```cpp
@@ -107,6 +169,39 @@ public:
};
```
+```cpp
+class Solution {
+public:
+ int beautySum(string s) {
+ int n = s.size();
+ int ans = 0;
+ for (int i = 0; i < n; ++i) {
+ int cnt[26]{};
+ unordered_map freq;
+ int mi = 1, mx = 1;
+ for (int j = i; j < n; ++j) {
+ int k = s[j] - 'a';
+ --freq[cnt[k]];
+ ++cnt[k];
+ ++freq[cnt[k]];
+
+ if (cnt[k] == 1) {
+ mi = 1;
+ }
+ if (freq[mi] == 0) {
+ ++mi;
+ }
+ if (cnt[k] > mx) {
+ mx = cnt[k];
+ }
+ ans += mx - mi;
+ }
+ }
+ return ans;
+ }
+};
+```
+
### **Go**
```go
@@ -133,6 +228,35 @@ func beautySum(s string) (ans int) {
}
```
+```go
+func beautySum(s string) (ans int) {
+ n := len(s)
+ for i := 0; i < n; i++ {
+ cnt := [26]int{}
+ freq := map[int]int{}
+ mi, mx := 1, 1
+ for j := i; j < n; j++ {
+ k := int(s[j] - 'a')
+ freq[cnt[k]]--
+ cnt[k]++
+ freq[cnt[k]]++
+
+ if cnt[k] == 1 {
+ mi = 1
+ }
+ if freq[mi] == 0 {
+ mi++
+ }
+ if cnt[k] > mx {
+ mx = cnt[k]
+ }
+ ans += mx - mi
+ }
+ }
+ return
+}
+```
+
### **JavaScript**
```js
@@ -154,6 +278,39 @@ var beautySum = function (s) {
};
```
+```js
+/**
+ * @param {string} s
+ * @return {number}
+ */
+var beautySum = function (s) {
+ const n = s.length;
+ let ans = 0;
+ for (let i = 0; i < n; ++i) {
+ const cnt = Array(26).fill(0);
+ const freq = new Map();
+ let [mi, mx] = [1, 1];
+ for (let j = i; j < n; ++j) {
+ const k = s[j].charCodeAt() - 97;
+ freq.set(cnt[k], (freq.get(cnt[k]) || 0) - 1);
+ ++cnt[k];
+ freq.set(cnt[k], (freq.get(cnt[k]) || 0) + 1);
+ if (cnt[k] === 1) {
+ mi = 1;
+ }
+ if (freq.get(mi) === 0) {
+ ++mi;
+ }
+ if (cnt[k] > mx) {
+ mx = cnt[k];
+ }
+ ans += mx - mi;
+ }
+ }
+ return ans;
+};
+```
+
### **...**
```
diff --git a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README.md b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README.md
index 600d2a40e84ae..59d740d71cee6 100644
--- a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README.md
+++ b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README.md
@@ -50,7 +50,7 @@
因此,只需要判断字符串 $s$ 是否存在 "01" 串即可。
-时间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。
+时间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。空间复杂度 $O(1)$。
diff --git a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md
index 1cd1410af7df5..a57363a24050c 100644
--- a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md
+++ b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md
@@ -32,6 +32,18 @@
## Solutions
+**Solution 1: No '1' After '0'**
+
+Notice that the string $s$ does not contain leading zeros, which means $s$ starts with '1'.
+
+If the string $s$ contains the substring "01", then $s$ must be a string like "1...01...", in which case $s$ has at least two consecutive '1' segments, which does not satisfy the problem condition, so we return `false`.
+
+If the string $s$ does not contain the substring "01", then $s$ can only be a string like "1..1000...", in which case $s$ has only one consecutive '1' segment, which satisfies the problem condition, so we return `true`.
+
+Therefore, we only need to judge whether the string $s$ contains the substring "01".
+
+The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README.md b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README.md
index da8796f0cca4f..ef10269b14063 100644
--- a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README.md
+++ b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README.md
@@ -52,7 +52,7 @@
注意,本题中数组元素的数据范围为 $[-10^6, 10^6]$,元素个数最大为 $10^5$,总和 $s$ 以及差值 $d$ 可能会超过 $32$ 位整数的表示范围,因此需要使用 $64$ 位整数。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。
+时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。
diff --git a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md
index 5fd46f899cf5d..b396d4e1d7667 100644
--- a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md
+++ b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md
@@ -38,6 +38,16 @@
## Solutions
+**Solution 1: Greedy**
+
+First, we calculate the sum of the array elements $s$, and then calculate the difference $d$ between $s$ and $goal$.
+
+The number of elements to be added is the absolute value of $d$ divided by $limit$ and rounded up, that is, $\lceil \frac{|d|}{limit} \rceil$.
+
+Note that in this problem, the data range of array elements is $[-10^6, 10^6]$, the maximum number of elements is $10^5$, the total sum $s$ and the difference $d$ may exceed the range of 32-bit integers, so we need to use 64-bit integers.
+
+The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$.
+
### **Python3**
diff --git a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README.md b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README.md
index efbab670f98e8..c3978224e0804 100644
--- a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README.md
+++ b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README.md
@@ -53,15 +53,15 @@
-**方法一:简单计数**
+**方法一:计数**
我们用变量 $cnt$ 记录两个字符串中相同位置字符不同的个数,两个字符串若满足题目要求,那么 $cnt$ 一定为 $0$ 或 $2$。另外用两个字符变量 $c1$ 和 $c2$ 记录两个字符串中相同位置字符不同的字符。
同时遍历两个字符串,对于相同位置的两个字符 $a$ 和 $b$,如果 $a \ne b$,那么 $cnt$ 自增 $1$。如果此时 $cnt$ 大于 $2$,或者 $cnt$ 为 $2$ 且 $a \ne c2$ 或 $b \ne c1$,那么直接返回 `false`。注意记录一下 $c1$ 和 $c2$。
-遍历结束,若 $cnt\neq 1$,返回 `true`。
+遍历结束,若 $cnt \neq 1$,返回 `true`。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串长度。
+时间复杂度 $O(n)$,其中 $n$ 为字符串长度。空间复杂度 $O(1)$。
diff --git a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md
index 9614b017125db..8600e6aa2752d 100644
--- a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md
+++ b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md
@@ -44,6 +44,16 @@
## Solutions
+**Solution 1: Counting**
+
+We use a variable $cnt$ to record the number of characters at the same position in the two strings that are different. If the two strings meet the requirements of the problem, then $cnt$ must be $0$ or $2$. We also use two character variables $c1$ and $c2$ to record the characters that are different at the same position in the two strings.
+
+While traversing the two strings simultaneously, for two characters $a$ and $b$ at the same position, if $a \ne b$, then $cnt$ is incremented by $1$. If at this time $cnt$ is greater than $2$, or $cnt$ is $2$ and $a \ne c2$ or $b \ne c1$, then we directly return `false`. Note to record $c1$ and $c2$.
+
+At the end of the traversal, if $cnt \neq 1$, return `true`.
+
+The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1700-1799/1791.Find Center of Star Graph/README.md b/solution/1700-1799/1791.Find Center of Star Graph/README.md
index 2c1faed3752f1..bf094088b5934 100644
--- a/solution/1700-1799/1791.Find Center of Star Graph/README.md
+++ b/solution/1700-1799/1791.Find Center of Star Graph/README.md
@@ -48,7 +48,7 @@
中心点的特点是,它与其他所有点都相连,因此只要比较前两条边的点,如果有相同的点,那么这个点就是中心点。
-时间复杂度 $O(1)$。
+时间复杂度 $O(1)$,空间复杂度 $O(1)$。
diff --git a/solution/1700-1799/1791.Find Center of Star Graph/README_EN.md b/solution/1700-1799/1791.Find Center of Star Graph/README_EN.md
index 25a2803449ef7..ef0388de2310d 100644
--- a/solution/1700-1799/1791.Find Center of Star Graph/README_EN.md
+++ b/solution/1700-1799/1791.Find Center of Star Graph/README_EN.md
@@ -38,6 +38,12 @@
## Solutions
+**Solution 1: Directly Compare the Points of the First Two Edges**
+
+The characteristic of the center point is that it is connected to all other points. Therefore, as long as we compare the points of the first two edges, if there are the same points, then this point is the center point.
+
+The time complexity is $O(1)$, and the space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1700-1799/1792.Maximum Average Pass Ratio/README.md b/solution/1700-1799/1792.Maximum Average Pass Ratio/README.md
index b81ea8d9b17ac..7d4cc11a23ff6 100644
--- a/solution/1700-1799/1792.Maximum Average Pass Ratio/README.md
+++ b/solution/1700-1799/1792.Maximum Average Pass Ratio/README.md
@@ -56,7 +56,7 @@
最后,我们将所有班级的通过率求和,然后除以班级数目,即为答案。
-时间复杂度 $O(n\log n)$,其中 $n$ 为班级数目。
+时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为班级数目。
diff --git a/solution/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md b/solution/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md
index 5af5e93dfcf50..7df629cd0146d 100644
--- a/solution/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md
+++ b/solution/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md
@@ -40,6 +40,18 @@
## Solutions
+**Solution 1: Priority Queue (Max-Heap of Increment)**
+
+Suppose a class currently has a pass rate of $\frac{a}{b}$. If we arrange a smart student into this class, then the pass rate of the class will become $\frac{a+1}{b+1}$. We can find that the increment of the pass rate is $\frac{a+1}{b+1} - \frac{a}{b}$.
+
+We maintain a max-heap, which stores the increment of the pass rate for each class.
+
+Perform `extraStudents` operations, each time taking a class from the top of the heap, adding $1$ to both the number of students and the number of passes in this class, then recalculating the increment of the pass rate of this class and putting it back into the heap. Repeat this process until all students are allocated.
+
+Finally, we sum up the pass rates of all classes, and then divide by the number of classes to get the answer.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of classes.
+
### **Python3**
diff --git a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README.md b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README.md
index a141722c837fb..6ea0d604d612d 100644
--- a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README.md
+++ b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README.md
@@ -160,6 +160,31 @@ func countQuadruples(firstString string, secondString string) (ans int) {
}
```
+### **TypeScript**
+
+```ts
+function countQuadruples(firstString: string, secondString: string): number {
+ const last: number[] = new Array(26).fill(0);
+ for (let i = 0; i < secondString.length; ++i) {
+ last[secondString.charCodeAt(i) - 97] = i + 1;
+ }
+ let [ans, mi] = [0, Infinity];
+ for (let i = 0; i < firstString.length; ++i) {
+ const j = last[firstString.charCodeAt(i) - 97];
+ if (j) {
+ const t = i - j;
+ if (mi > t) {
+ mi = t;
+ ans = 1;
+ } else if (mi === t) {
+ ++ans;
+ }
+ }
+ }
+ return ans;
+}
+```
+
### **...**
```
diff --git a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md
index bdaa7865ea149..992312b4063df 100644
--- a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md
+++ b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md
@@ -42,6 +42,14 @@
## Solutions
+**Solution 1: Greedy + Hash Table**
+
+The problem actually asks us to find a smallest index $i$ and a largest index $j$ such that $firstString[i]$ equals $secondString[j]$, and the value of $i - j$ is the smallest among all index pairs that meet the conditions.
+
+Therefore, we first use a hash table $last$ to record the index of the last occurrence of each character in $secondString$. Then we traverse $firstString$. For each character $c$, if $c$ has appeared in $secondString$, we calculate $i - last[c]$. If the value of $i - last[c]$ is less than the current minimum value, we update the minimum value and set the answer to 1. If the value of $i - last[c]$ equals the current minimum value, we increment the answer by 1.
+
+The time complexity is $O(m + n)$, and the space complexity is $O(C)$. Here, $m$ and $n$ are the lengths of $firstString$ and $secondString$ respectively, and $C$ is the size of the character set. In this problem, $C = 26$.
+
### **Python3**
@@ -142,6 +150,31 @@ func countQuadruples(firstString string, secondString string) (ans int) {
}
```
+### **TypeScript**
+
+```ts
+function countQuadruples(firstString: string, secondString: string): number {
+ const last: number[] = new Array(26).fill(0);
+ for (let i = 0; i < secondString.length; ++i) {
+ last[secondString.charCodeAt(i) - 97] = i + 1;
+ }
+ let [ans, mi] = [0, Infinity];
+ for (let i = 0; i < firstString.length; ++i) {
+ const j = last[firstString.charCodeAt(i) - 97];
+ if (j) {
+ const t = i - j;
+ if (mi > t) {
+ mi = t;
+ ans = 1;
+ } else if (mi === t) {
+ ++ans;
+ }
+ }
+ }
+ return ans;
+}
+```
+
### **...**
```
diff --git a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/Solution.ts b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/Solution.ts
new file mode 100644
index 0000000000000..fde8e1274b21a
--- /dev/null
+++ b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/Solution.ts
@@ -0,0 +1,20 @@
+function countQuadruples(firstString: string, secondString: string): number {
+ const last: number[] = new Array(26).fill(0);
+ for (let i = 0; i < secondString.length; ++i) {
+ last[secondString.charCodeAt(i) - 97] = i + 1;
+ }
+ let [ans, mi] = [0, Infinity];
+ for (let i = 0; i < firstString.length; ++i) {
+ const j = last[firstString.charCodeAt(i) - 97];
+ if (j) {
+ const t = i - j;
+ if (mi > t) {
+ mi = t;
+ ans = 1;
+ } else if (mi === t) {
+ ++ans;
+ }
+ }
+ }
+ return ans;
+}
diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/README.md b/solution/1700-1799/1796.Second Largest Digit in a String/README.md
index 9820772378396..f687064bfa79d 100644
--- a/solution/1700-1799/1796.Second Largest Digit in a String/README.md
+++ b/solution/1700-1799/1796.Second Largest Digit in a String/README.md
@@ -49,7 +49,7 @@
遍历结束,返回 $b$ 即可。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。
+时间复杂度 $O(n)$,其中 $n$ 为字符串 $s$ 的长度。空间复杂度 $O(1)$。
**方法二:位运算**
@@ -59,7 +59,7 @@
最后,我们从高位向低位遍历 $mask$,找到第二个为 $1$ 的二进制位,其对应的数字即为第二大数字。如果不存在第二大数字,返回 $-1$。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。
+时间复杂度 $O(n)$,其中 $n$ 为字符串 $s$ 的长度。空间复杂度 $O(1)$。
diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/README_EN.md b/solution/1700-1799/1796.Second Largest Digit in a String/README_EN.md
index 7daff59d51886..901df4778eb42 100644
--- a/solution/1700-1799/1796.Second Largest Digit in a String/README_EN.md
+++ b/solution/1700-1799/1796.Second Largest Digit in a String/README_EN.md
@@ -35,6 +35,26 @@
## Solutions
+**Solution 1: One Pass**
+
+We define $a$ and $b$ to represent the largest and second largest numbers in the string, initially $a = b = -1$.
+
+We traverse the string $s$. If the current character is a digit, we convert it to a number $v$. If $v > a$, it means that $v$ is the largest number currently appearing, we update $b$ to $a$, and update $a$ to $v$; if $v < a$, it means that $v$ is the second largest number currently appearing, we update $b$ to $v$.
+
+After the traversal, we return $b$.
+
+The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.
+
+**Solution 2: Bit Manipulation**
+
+We can use an integer $mask$ to mark the numbers that appear in the string, where the $i$-th bit of $mask$ indicates whether the number $i$ has appeared.
+
+We traverse the string $s$. If the current character is a digit, we convert it to a number $v$, and set the $v$-th bit of $mask$ to $1$.
+
+Finally, we traverse $mask$ from high to low, find the second bit that is $1$, and the corresponding number is the second largest number. If there is no second largest number, return $-1$.
+
+The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1700-1799/1797.Design Authentication Manager/README_EN.md b/solution/1700-1799/1797.Design Authentication Manager/README_EN.md
index b0a12cbf17e1e..0f11ff8f01cd6 100644
--- a/solution/1700-1799/1797.Design Authentication Manager/README_EN.md
+++ b/solution/1700-1799/1797.Design Authentication Manager/README_EN.md
@@ -54,6 +54,18 @@ authenticationManager.countUnexpiredTokens(15); // The token with t
## Solutions
+**Solution 1: Hash Table**
+
+We can simply maintain a hash table $d$, where the key is `tokenId` and the value is the expiration time.
+
+- During the `generate` operation, we store `tokenId` as the key and `currentTime + timeToLive` as the value in the hash table $d$.
+- During the `renew` operation, if `tokenId` is not in the hash table $d$, or `currentTime >= d[tokenId]`, we ignore this operation; otherwise, we update `d[tokenId]` to `currentTime + timeToLive`.
+- During the `countUnexpiredTokens` operation, we traverse the hash table $d$ and count the number of unexpired `tokenId`.
+
+In terms of time complexity, both `generate` and `renew` operations have a time complexity of $O(1)$, and the `countUnexpiredTokens` operation has a time complexity of $O(n)$, where $n$ is the number of key-value pairs in the hash table $d$.
+
+The space complexity is $O(n)$, where $n$ is the number of key-value pairs in the hash table $d$.
+
### **Python3**
diff --git a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README.md b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README.md
index 2f6b67a435ad0..d6fffa4261e52 100644
--- a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README.md
+++ b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README.md
@@ -140,6 +140,22 @@ func getMaximumConsecutive(coins []int) int {
}
```
+### **TypeScript**
+
+```ts
+function getMaximumConsecutive(coins: number[]): number {
+ coins.sort((a, b) => a - b);
+ let ans = 1;
+ for (const v of coins) {
+ if (v > ans) {
+ break;
+ }
+ ans += v;
+ }
+ return ans;
+}
+```
+
### **...**
```
diff --git a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md
index d25f4cc434df2..9c716ae53f87a 100644
--- a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md
+++ b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md
@@ -54,6 +54,16 @@ You can make 8 consecutive integer values starting from 0.
## Solutions
+**Solution 1: Sorting + Greedy**
+
+First, we sort the array. Then we define $ans$ as the current number of consecutive integers that can be constructed, initialized to $1$.
+
+We traverse the array, for the current element $v$, if $v > ans$, it means that we cannot construct $ans+1$ consecutive integers, so we directly break the loop and return $ans$. Otherwise, it means that we can construct $ans+v$ consecutive integers, so we update $ans$ to $ans+v$.
+
+Finally, we return $ans$.
+
+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.
+
### **Python3**
@@ -120,6 +130,22 @@ func getMaximumConsecutive(coins []int) int {
}
```
+### **TypeScript**
+
+```ts
+function getMaximumConsecutive(coins: number[]): number {
+ coins.sort((a, b) => a - b);
+ let ans = 1;
+ for (const v of coins) {
+ if (v > ans) {
+ break;
+ }
+ ans += v;
+ }
+ return ans;
+}
+```
+
### **...**
```
diff --git a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/Solution.ts b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/Solution.ts
new file mode 100644
index 0000000000000..298ae5e05d03a
--- /dev/null
+++ b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/Solution.ts
@@ -0,0 +1,11 @@
+function getMaximumConsecutive(coins: number[]): number {
+ coins.sort((a, b) => a - b);
+ let ans = 1;
+ for (const v of coins) {
+ if (v > ans) {
+ break;
+ }
+ ans += v;
+ }
+ return ans;
+}
diff --git a/solution/1700-1799/1799.Maximize Score After N Operations/README_EN.md b/solution/1700-1799/1799.Maximize Score After N Operations/README_EN.md
index 467c318b4734e..ba05525821a69 100644
--- a/solution/1700-1799/1799.Maximize Score After N Operations/README_EN.md
+++ b/solution/1700-1799/1799.Maximize Score After N Operations/README_EN.md
@@ -57,6 +57,20 @@
## Solutions
+**Solution 1: State Compression + Dynamic Programming**
+
+We can preprocess to get the greatest common divisor of any two numbers in the array `nums`, stored in the two-dimensional array $g$, where $g[i][j]$ represents the greatest common divisor of $nums[i]$ and $nums[j]$.
+
+Then define $f[k]$ to represent the maximum score that can be obtained when the state after the current operation is $k$. Suppose $m$ is the number of elements in the array `nums`, then there are a total of $2^m$ states, that is, the range of $k$ is $[0, 2^m - 1]$.
+
+Enumerate all states from small to large, for each state $k$, first determine whether the number of $1$s in the binary bits of this state $cnt$ is even, if so, perform the following operations:
+
+Enumerate the positions where the binary bits in $k$ are 1, suppose they are $i$ and $j$, then the elements at positions $i$ and $j$ can perform one operation, and the score that can be obtained at this time is $\frac{cnt}{2} \times g[i][j]$, update the maximum value of $f[k]$.
+
+The final answer is $f[2^m - 1]$.
+
+The time complexity is $O(2^m \times m^2)$, and the space complexity is $O(2^m)$. Here, $m$ is the number of elements in the array `nums`.
+
### **Python3**
diff --git a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README.md b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README.md
index d25918eb79c27..9db6c877f825e 100644
--- a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README.md
+++ b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README.md
@@ -60,15 +60,15 @@
**方法一:直接模拟**
-我们用变量 `t` 记录当前升序子数组的和,用变量 `ans` 记录最大的升序子数组和。
+我们用变量 $t$ 记录当前升序子数组的和,用变量 $ans$ 记录最大的升序子数组和。
-遍历数组 `nums`:
+遍历数组 $nums$:
-如果当前元素是数组的第一个元素,或者当前元素大于前一个元素,那么将当前元素加入到当前升序子数组的和,即 `t += nums[i]`,并且更新最大升序子数组和 `ans = max(ans, t)`;否则,当前元素不满足升序子数组的条件,那么将当前升序子数组的和 `t` 重置为当前元素,即 `t = nums[i]`。
+如果当前元素是数组的第一个元素,或者当前元素大于前一个元素,那么将当前元素加入到当前升序子数组的和,即 $t = t + nums[i]$,并且更新最大升序子数组和 $ans = \max(ans, t)$;否则,当前元素不满足升序子数组的条件,那么将当前升序子数组的和 $t$ 重置为当前元素,即 $t = nums[i]$。
-遍历结束,返回最大升序子数组和 `ans`。
+遍历结束,返回最大升序子数组和 $ans$。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。
+时间复杂度 $O(n)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md
index 9d88298272b13..b49337e100f2d 100644
--- a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md
+++ b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md
@@ -45,6 +45,18 @@
## Solutions
+**Solution 1: Direct Simulation**
+
+We use a variable $t$ to record the current sum of the ascending subarray, and a variable $ans$ to record the maximum sum of the ascending subarray.
+
+Traverse the array $nums$:
+
+If the current element is the first element of the array, or the current element is greater than the previous one, then add the current element to the sum of the current ascending subarray, i.e., $t = t + nums[i]$, and update the maximum sum of the ascending subarray $ans = \max(ans, t)$. Otherwise, the current element does not satisfy the condition of the ascending subarray, so reset the sum $t$ of the current ascending subarray to the current element, i.e., $t = nums[i]$.
+
+After the traversal, return the maximum sum of the ascending subarray $ans$.
+
+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/1800-1899/1801.Number of Orders in the Backlog/README_EN.md b/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md
index d348ea8fc343e..9fc03f54a15e1 100644
--- a/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md
+++ b/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md
@@ -61,6 +61,16 @@ Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995
## Solutions
+**Solution 1: Priority Queue (Max-Min Heap) + Simulation**
+
+We can use a priority queue (max-min heap) to maintain the current backlog of orders, where the max heap `buy` maintains the backlog of purchase orders, and the min heap `sell` maintains the backlog of sales orders. Each element in the heap is a tuple $(price, amount)$, indicating that the number of orders at price `price` is `amount`.
+
+Next, we traverse the order array `orders`, and simulate according to the problem's requirements.
+
+After the traversal, we add the order quantities in `buy` and `sell`, which is the final backlog of orders. Note that the answer may be very large, so we need to take the modulus of $10^9 + 7$.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of `orders`.
+
### **Python3**
diff --git a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md
index c9f763dc5cafd..bbe53f1fe2603 100644
--- a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md
+++ b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md
@@ -63,7 +63,7 @@
最后将 $left$ 作为答案返回即可。
-时间复杂度 $O(\log M)$,空间复杂度 $O(1)$。其中 $M=maxSum$。
+时间复杂度 $O(\log M)$,其中 $M=maxSum$。空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md
index 573d91b9f1668..1fbde3299aa1b 100644
--- a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md
+++ b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md
@@ -45,6 +45,23 @@ There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2
## Solutions
+**Solution 1: Binary Search**
+
+According to the problem description, if we determine the value of $nums[index]$ as $x$, we can find a minimum array sum. That is, the elements on the left side of $index$ in the array decrease from $x-1$ to $1$, and if there are remaining elements, the remaining elements are all $1$; similarly, the elements at $index$ and on the right side of the array decrease from $x$ to $1$, and if there are remaining elements, the remaining elements are all $1$.
+
+In this way, we can calculate the sum of the array. If the sum is less than or equal to $maxSum$, then the current $x$ is valid. As $x$ increases, the sum of the array will also increase, so we can use the binary search method to find the maximum $x$ that meets the conditions.
+
+To facilitate the calculation of the sum of the elements on the left and right sides of the array, we define a function $sum(x, cnt)$, which represents the sum of an array with $cnt$ elements and a maximum value of $x$. The function $sum(x, cnt)$ can be divided into two cases:
+
+- If $x \geq cnt$, then the sum of the array is $\frac{(x + x - cnt + 1) \times cnt}{2}$
+- If $x \lt cnt$, then the sum of the array is $\frac{(x + 1) \times x}{2} + cnt - x$
+
+Next, define the left boundary of the binary search as $left = 1$, the right boundary as $right = maxSum$, and then binary search for the value $mid$ of $nums[index]$. If $sum(mid - 1, index) + sum(mid, n - index) \leq maxSum$, then the current $mid$ is valid, we can update $left$ to $mid$, otherwise we update $right$ to $mid - 1$.
+
+Finally, return $left$ as the answer.
+
+The time complexity is $O(\log M)$, where $M=maxSum$. The space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md b/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md
index 8e2f5405a0b20..ec418767ff1d6 100644
--- a/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md
+++ b/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md
@@ -49,6 +49,31 @@
## Solutions
+**Solution 1: 0-1 Trie**
+
+For this kind of problem that counts the interval $[low, high]$, we can consider converting it into counting $[0, high]$ and $[0, low - 1]$, and then subtracting the latter from the former to get the answer.
+
+In this problem, we can count how many pairs of numbers have an XOR value less than $high+1$, and then count how many pairs of numbers have an XOR value less than $low$. The difference between these two counts is the number of pairs whose XOR value is in the interval $[low, high]$.
+
+Moreover, for array XOR counting problems, we can usually use a "0-1 Trie" to solve them.
+
+The definition of the Trie node is as follows:
+
+- `children[0]` and `children[1]` represent the left and right child nodes of the current node, respectively;
+- `cnt` represents the number of numbers ending with the current node.
+
+In the Trie, we also define the following two functions:
+
+One function is $insert(x)$, which inserts the number $x$ into the Trie. This function inserts the number $x$ into the "0-1 Trie" in the order of binary bits from high to low. If the current binary bit is $0$, it is inserted into the left child node, otherwise, it is inserted into the right child node. Then the count value $cnt$ of the node is increased by $1$.
+
+Another function is $search(x, limit)$, which searches for the count of numbers in the Trie that have an XOR value with $x$ less than $limit$. This function starts from the root node `node` of the Trie, traverses the binary bits of $x$ from high to low, and denotes the current binary bit of $x$ as $v$. If the current binary bit of $limit$ is $1$, we can directly add the count value $cnt$ of the child node that has the same binary bit $v$ as $x$ to the answer, and then move the current node to the child node that has a different binary bit $v$ from $x$, i.e., `node = node.children[v ^ 1]`. Continue to traverse the next bit. If the current binary bit of $limit$ is $0$, we can only move the current node to the child node that has the same binary bit $v$ as $x$, i.e., `node = node.children[v]`. Continue to traverse the next bit. After traversing the binary bits of $x$, return the answer.
+
+With the above two functions, we can solve this problem.
+
+We traverse the array `nums`. For each number $x$, we first search in the Trie for the count of numbers that have an XOR value with $x$ less than $high+1$, and then search in the Trie for the count of pairs that have an XOR value with $x$ less than $low$, and add the difference between the two counts to the answer. Then insert $x$ into the Trie. Continue to traverse the next number $x$ until the array `nums` is traversed. Finally, return the answer.
+
+The time complexity is $O(n \times \log M)$, and the space complexity is $O(n \times \log M)$. Here, $n$ is the length of the array `nums`, and $M$ is the maximum value in the array `nums`. In this problem, we directly take $\log M = 16$.
+
### **Python3**
diff --git a/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md b/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md
index b615b0ddcec8f..eb3a06340bfa5 100644
--- a/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md
+++ b/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md
@@ -51,6 +51,42 @@ trie.countWordsStartingWith("app"); // return 0
## Solutions
+**Solution 1: Implement Trie with Array**
+
+Each node in the Trie includes three parts:
+
+1. An array of pointers `children` pointing to child nodes. For this problem, the array length is 26, which is the number of lowercase English letters. `children[0]` corresponds to the lowercase letter a, ..., `children[25]` corresponds to the lowercase letter z.
+1. An int variable `v`, representing the number of strings ending with this node.
+1. An int variable `pv`, representing the number of strings with this node as the prefix node.
+
+### 1. Insert String
+
+We start from the root of the Trie and insert the string. For the child node corresponding to the current character, there are two cases:
+
+- The child node exists. Move to the child node along the pointer and continue to process the next character.
+- The child node does not exist. Create a new child node, record it in the corresponding position of the `children` array, then move to the child node along the pointer, and increase the `pv` value of the child node by 1. Continue to search for the next character.
+
+Repeat the above steps until the last character of the string is processed, then increase the `v` value of the current node by 1.
+
+The time complexity is $O(n)$, where $n$ is the length of the string.
+
+### 2. Search Prefix
+
+We start from the root of the Trie and search for the prefix. For the child node corresponding to the current character, there are two cases:
+
+- The child node exists. Move to the child node along the pointer and continue to search for the next character.
+- The child node does not exist. This means that the Trie does not contain this prefix, return a null pointer.
+
+Repeat the above steps until a null pointer is returned or the last character of the prefix is searched.
+
+The time complexity is $O(n)$, where $n$ is the length of the string.
+
+### 3. Remove String
+
+We start from the root node of the Trie, and sequentially reduce the `pv` value of the corresponding child node by 1, until the last character of the string is searched. Then reduce the `v` value of the current node by 1.
+
+The time complexity is $O(n)$, where $n$ is the length of the string.
+
### **Python3**
diff --git a/solution/1800-1899/1805.Number of Different Integers in a String/README_EN.md b/solution/1800-1899/1805.Number of Different Integers in a String/README_EN.md
index 835c1047ea976..cb7d8d4a3ad19 100644
--- a/solution/1800-1899/1805.Number of Different Integers in a String/README_EN.md
+++ b/solution/1800-1899/1805.Number of Different Integers in a String/README_EN.md
@@ -47,6 +47,16 @@ the leading zeros are ignored when comparing their decimal values.
## Solutions
+**Solution 1: Double Pointers + Simulation**
+
+Traverse the string `word`, find the start and end positions of each integer, cut out this substring, and store it in the hash set $s$.
+
+After the traversal, return the size of the hash set $s$.
+
+> Note, the integer represented by each substring may be very large, we cannot directly convert it to an integer. Therefore, we can remove the leading zeros of each substring before storing it in the hash set.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string `word`.
+
### **Python3**
diff --git a/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md b/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md
index 88857117ffde9..a6445ba262d44 100644
--- a/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md
+++ b/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md
@@ -56,6 +56,21 @@ So it takes only 2 operations.
## Solutions
+**Solution 1: Find Pattern + Simulation**
+
+We observe the change pattern of the numbers and find that:
+
+1. The even-indexed numbers of the new array are the numbers in the first half of the original array in order;
+1. The odd-indexed numbers of the new array are the numbers in the second half of the original array in order.
+
+That is, if the index $i$ of a number in the original array is in the range `[0, n >> 1)`, then the new index of this number is `i << 1`; otherwise, the new index is `(i - (n >> 1)) << 1 | 1`.
+
+In addition, the path of number movement is the same in each round of operation. As long as a number (except for numbers $0$ and $n-1$) returns to its original position, the entire sequence will be consistent with the previous one.
+
+Therefore, we choose the number $1$, whose initial index is also $1$. Each time we move the number $1$ to a new position, until the number $1$ returns to its original position, we can get the minimum number of operations.
+
+The time complexity is $O(n)$, and the space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md b/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md
index ada3889571382..20ce8b2df0a7b 100644
--- a/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md
+++ b/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md
@@ -70,6 +70,14 @@ Notice that the "a"s not in a bracket pair are not evaluated.
## Solutions
+**Solution 1: Hash Table + Simulation**
+
+First, we use a hash table $d$ to record the key-value pairs in `knowledge`.
+
+Then we traverse the string $s$. If the current character is an open parenthesis `'('`, we start traversing from the current position until we encounter a close parenthesis `')'`. At this point, the string within the parentheses is the key. We look for the corresponding value of this key in the hash table $d$. If found, we replace the value within the parentheses with it, otherwise, we replace it with `'?'`.
+
+The time complexity is $O(n + m)$, and the space complexity is $O(L)$. Here, $n$ and $m$ are the lengths of the string $s$ and the list `knowledge` respectively, and $L$ is the sum of the lengths of all strings in `knowledge`.
+
### **Python3**
diff --git a/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md b/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md
index 7ac14cc8046a9..e011744cdf904 100644
--- a/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md
+++ b/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md
@@ -42,6 +42,23 @@ There is not other value of n that has at most 5 prime factors and more nice div
## Solutions
+**Solution 1: Problem Transformation + Fast Power**
+
+We can factorize $n$ into prime factors, i.e., $n = a_1^{k_1} \times a_2^{k_2} \times\cdots \times a_m^{k_m}$, where $a_i$ is a prime factor and $k_i$ is the exponent of the prime factor $a_i$. Since the number of prime factors of $n$ does not exceed `primeFactors`, we have $k_1 + k_2 + \cdots + k_m \leq primeFactors$.
+
+According to the problem description, we know that a good factor of $n$ must be divisible by all prime factors, which means that a good factor of $n$ needs to include $a_1 \times a_2 \times \cdots \times a_m$ as a factor. Then the number of good factors $k= k_1 \times k_2 \times \cdots \times k_m$, i.e., $k$ is the product of $k_1, k_2, \cdots, k_m$. To maximize the number of good factors, we need to split `primeFactors` into $k_1, k_2, \cdots, k_m$ to make $k_1 \times k_2 \times \cdots \times k_m$ the largest. Therefore, the problem is transformed into: split the integer `primeFactors` into the product of several integers to maximize the product.
+
+Next, we just need to discuss different cases.
+
+- If $primeFactors \lt 4$, then directly return `primeFactors`.
+- If $primeFactors$ is a multiple of $3$, then we split `primeFactors` into multiples of $3$, i.e., $3^{\frac{primeFactors}{3}}$.
+- If $primeFactors$ modulo $3$ equals $1$, then we split `primeFactors` into $\frac{primeFactors}{3} - 1$ multiples of $3$, and then multiply by $4$, i.e., $3^{\frac{primeFactors}{3} - 1} \times 4$.
+- If $primeFactors$ modulo $3$ equals $2$, then we split `primeFactors` into $\frac{primeFactors}{3}$ multiples of $3$, and then multiply by $2$, i.e., $3^{\frac{primeFactors}{3}} \times 2$.
+
+In the above process, we use fast power to calculate the modulus.
+
+The time complexity is $O(\log n)$, and the space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1812.Determine Color of a Chessboard Square/README.md b/solution/1800-1899/1812.Determine Color of a Chessboard Square/README.md
index dc0e5c358a38a..d041ac9c64815 100644
--- a/solution/1800-1899/1812.Determine Color of a Chessboard Square/README.md
+++ b/solution/1800-1899/1812.Determine Color of a Chessboard Square/README.md
@@ -59,7 +59,7 @@
因此,我们可以根据 `coordinates` 获取对应的坐标 $(x, y)$,如果 $x + y$ 为奇数,则格子为白色,返回 `true`,否则返回 `false`。
-时间复杂度 $O(1)$。
+时间复杂度 $O(1)$,空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md b/solution/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md
index 5aaf1b496589f..8504ef7ccf717 100644
--- a/solution/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md
+++ b/solution/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md
@@ -47,6 +47,14 @@
## Solutions
+**Solution 1: Find the Pattern**
+
+By observing the chessboard, we find that two squares $(x_1, y_1)$ and $(x_2, y_2)$ with the same color satisfy that both $x_1 + y_1$ and $x_2 + y_2$ are either odd or even.
+
+Therefore, we can get the corresponding coordinates $(x, y)$ from `coordinates`. If $x + y$ is odd, then the square is white, return `true`, otherwise return `false`.
+
+The time complexity is $O(1)$, and the space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md b/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md
index 080ee1e428334..66664be34c575 100644
--- a/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md
+++ b/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md
@@ -37,6 +37,23 @@
## Solutions
+**Solution 1: Greedy + State Compression + Memorized Search**
+
+The problem actually asks us to find an arrangement order that maximizes the number of groups whose prefix sum (referring to "number of people" here) modulo $batchSize$ equals $0$. Therefore, we can divide all customers into two categories:
+
+- Customers whose number is a multiple of $batchSize$. These customers will not affect the donuts of the next group of customers. We can greedily arrange these groups of customers first, so these groups of customers will be happy. The "initial answer" is the number of these groups.
+- Customers whose number is not a multiple of $batchSize$. The arrangement order of these customers will affect the donuts of the next group of customers. We can take the modulo $batchSize$ for the number of people $v$ in each group here, and the remainders form a set. The range of element values in the set is $[1,2...,batchSize-1]$. The maximum length of the $groups$ array is $30$, so the maximum number of each remainder does not exceed $30$. We can use $5$ binary bits to represent the quantity of a remainder, and the maximum $batchSize$ is $9$, so the total number of binary bits required to represent these remainders and their quantities is $5\times (9-1)=40$. We can use a $64$-bit integer $state$ to represent it.
+
+Next, we design a function $dfs(state, mod)$, which represents the number of groups that can be happy when the arrangement state is $state$ and the current prefix remainder is $mod$. Then our "initial answer" plus $dfs(state, 0)$ is the final answer.
+
+The implementation logic of the function $dfs(state, mod)$ is as follows:
+
+We enumerate each remainder $i$ from $1$ to $batchSize-1$. If the quantity of the remainder $i$ is not $0$, we can subtract $1$ from the quantity of the remainder $i$, add $i$ to the current prefix remainder and take modulo $batchSize$, then recursively call the function $dfs$ to find the optimal solution of the sub-state, and take the maximum value. Finally, check whether $mod$ is $0$. If it is $0$, we return after adding $1$ to the maximum value, otherwise we directly return the maximum value.
+
+During the process, we can use memorized search to avoid repeated calculation of states.
+
+The time complexity does not exceed $O(10^7)$, and the space complexity does not exceed $O(10^6)$.
+
### **Python3**
diff --git a/solution/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md b/solution/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md
index 1ddf03d4a1848..04bb97ce0811e 100644
--- a/solution/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md
+++ b/solution/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md
@@ -61,7 +61,15 @@ This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1|
## Solutions
-Binary search.
+**Solution 1: Sorting + Binary Search**
+
+According to the problem, we can first calculate the absolute difference sum of `nums1` and `nums2` without any replacements, denoted as $s$.
+
+Next, we enumerate each element $nums1[i]$ in `nums1`, replacing it with the element closest to $nums2[i]$ that also exists in `nums1`. Therefore, before the enumeration, we can make a copy of `nums1`, resulting in the array `nums`, and sort `nums`. Then, we perform a binary search in `nums` for the element closest to $nums2[i]$, denoted as $nums[j]$, and calculate $|nums1[i] - nums2[i]| - |nums[j] - nums2[i]|$, updating the maximum value of the difference $mx$.
+
+Finally, we subtract $mx$ from $s$, which is the answer. Note the modulus operation.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `nums1`.
diff --git a/solution/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md b/solution/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md
index 0ff910c5ca727..40be4c785fe91 100644
--- a/solution/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md
+++ b/solution/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md
@@ -47,6 +47,16 @@ The different GCDs are 6, 10, 3, 2, and 1.
## Solutions
+**Solution 1: Enumeration + Mathematics**
+
+For all sub-sequences of the array $nums$, their greatest common divisor (GCD) will not exceed the maximum value $mx$ in the array.
+
+Therefore, we can enumerate each number $x$ in $[1,.. mx]$, and determine whether $x$ is the GCD of a sub-sequence of the array $nums$. If it is, then we increment the answer by one.
+
+So the problem is transformed into: determining whether $x$ is the GCD of a sub-sequence of the array $nums$. We can do this by enumerating the multiples $y$ of $x$, and checking whether $y$ exists in the array $nums$. If $y$ exists in the array $nums$, then we calculate the GCD $g$ of $y$. If $g = x$ occurs, then $x$ is the GCD of a sub-sequence of the array $nums$.
+
+The time complexity is $O(n + M \times \log M)$, and the space complexity is $O(M)$. Here, $n$ and $M$ are the length of the array $nums$ and the maximum value in the array $nums$, respectively.
+
### **Python3**
diff --git a/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README.md b/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README.md
index 854755746c480..dc9d2c9fe701c 100644
--- a/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README.md
+++ b/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README.md
@@ -59,7 +59,7 @@
匈牙利算法的核心思想是,不断地从未匹配的点出发,寻找增广路径,直到没有增广路径为止,就得到了最大匹配。
-时间复杂度 $O(m\times n)$。
+时间复杂度 $O(m \times n)$。
diff --git a/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md b/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md
index db6881352a90e..2d6ad590aed01 100644
--- a/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md
+++ b/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md
@@ -49,6 +49,14 @@ Explanation: The invitations are sent as follows:
## Solutions
+**Solution 1: Hungarian Algorithm**
+
+This problem belongs to the maximum matching problem of bipartite graphs, which is suitable for solving with the Hungarian algorithm.
+
+The core idea of the Hungarian algorithm is to continuously start from unmatched points, look for augmenting paths, and stop when there are no augmenting paths. This gives the maximum match.
+
+The time complexity is $O(m \times n)$.
+
### **Python3**
diff --git a/solution/1800-1899/1824.Minimum Sideway Jumps/README.md b/solution/1800-1899/1824.Minimum Sideway Jumps/README.md
index 4c1588eabc428..7da74ee8bc0a9 100644
--- a/solution/1800-1899/1824.Minimum Sideway Jumps/README.md
+++ b/solution/1800-1899/1824.Minimum Sideway Jumps/README.md
@@ -76,7 +76,7 @@
在代码实现上,我们可以将第一维空间优化掉,只用一个长度为 $3$ 的数组 $f$ 来维护。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $obstacles$ 的长度。
+时间复杂度 $O(n)$,其中 $n$ 为数组 $obstacles$ 的长度。空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1824.Minimum Sideway Jumps/README_EN.md b/solution/1800-1899/1824.Minimum Sideway Jumps/README_EN.md
index eb067bd326f69..dcb9055bfb502 100644
--- a/solution/1800-1899/1824.Minimum Sideway Jumps/README_EN.md
+++ b/solution/1800-1899/1824.Minimum Sideway Jumps/README_EN.md
@@ -60,6 +60,18 @@ Note that the frog can jump over obstacles only when making side jumps (as shown
## Solutions
+**Solution 1: Dynamic Programming**
+
+We define $f[i][j]$ as the minimum number of sidesteps for the frog to reach the $i$-th point and be on the $j$-th lane (index starts from $0$).
+
+Note that the frog starts on the second lane (the problem index starts from $1$), so the value of $f[0][1]$ is $0$, and the values of $f[0][0]$ and $f[0][2]$ are both $1$. The answer is $min(f[n][0], f[n][1], f[n][2])$.
+
+For each position $i$ from $1$ to $n$, we can enumerate the current lane $j$ of the frog. If $obstacles[i] = j + 1$, it means that there is an obstacle on the $j$-th lane, and the value of $f[i][j]$ is infinity. Otherwise, the frog can choose not to jump, in which case the value of $f[i][j]$ is $f[i - 1][j]$, or the frog can sidestep from other lanes, in which case $f[i][j] = min(f[i][j], min(f[i][0], f[i][1], f[i][2]) + 1)$.
+
+In the code implementation, we can optimize the first dimension of space and only use an array $f$ of length $3$ for maintenance.
+
+The time complexity is $O(n)$, where $n$ is the length of the array $obstacles$. The space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1825.Finding MK Average/README_EN.md b/solution/1800-1899/1825.Finding MK Average/README_EN.md
index 9d7c46e09565a..9443d06f8f471 100644
--- a/solution/1800-1899/1825.Finding MK Average/README_EN.md
+++ b/solution/1800-1899/1825.Finding MK Average/README_EN.md
@@ -61,6 +61,28 @@ obj.calculateMKAverage(); // The last 3 elements are [5,5,5].
## Solutions
+**Solution 1: Ordered Set + Queue**
+
+We can maintain the following data structures or variables:
+
+- A queue $q$ of length $m$, where the head of the queue is the earliest added element, and the tail of the queue is the most recently added element;
+- Three ordered sets, namely $lo$, $mid$, $hi$, where $lo$ and $hi$ store the smallest $k$ elements and the largest $k$ elements respectively, and $mid$ stores the remaining elements;
+- A variable $s$, maintaining the sum of all elements in $mid$;
+- Some programming languages (such as Java, Go) additionally maintain two variables $size1$ and $size3$, representing the number of elements in $lo$ and $hi$ respectively.
+
+When calling the $addElement(num)$ function, perform the following operations in order:
+
+1. If $lo$ is empty, or $num \leq max(lo)$, then add $num$ to $lo$; otherwise if $hi$ is empty, or $num \geq min(hi)$, then add $num$ to $hi$; otherwise add $num$ to $mid$, and add the value of $num$ to $s$.
+1. Next, add $num$ to the queue $q$. If the length of the queue $q$ is greater than $m$ at this time, remove the head element $x$ from the queue $q$, then choose one of $lo$, $mid$ or $hi$ that contains $x$, and remove $x$ from this set. If the set is $mid$, subtract the value of $x$ from $s$.
+1. If the length of $lo$ is greater than $k$, then repeatedly remove the maximum value $max(lo)$ from $lo$, add $max(lo)$ to $mid$, and add the value of $max(lo)$ to $s$.
+1. If the length of $hi$ is greater than $k$, then repeatedly remove the minimum value $min(hi)$ from $hi$, add $min(hi)$ to $mid$, and add the value of $min(hi)$ to $s$.
+1. If the length of $lo$ is less than $k$ and $mid$ is not empty, then repeatedly remove the minimum value $min(mid)$ from $mid$, add $min(mid)$ to $lo$, and subtract the value of $min(mid)$ from $s$.
+1. If the length of $hi$ is less than $k$ and $mid$ is not empty, then repeatedly remove the maximum value $max(mid)$ from $mid$, add $max(mid)$ to $hi$, and subtract the value of $max(mid)$ from $s$.
+
+When calling the $calculateMKAverage()$ function, if the length of $q$ is less than $m$, return $-1$, otherwise return $\frac{s}{m - 2k}$.
+
+In terms of time complexity, each call to the $addElement(num)$ function has a time complexity of $O(\log m)$, and each call to the $calculateMKAverage()$ function has a time complexity of $O(1)$. The space complexity is $O(m)$.
+
### **Python3**
diff --git a/solution/1800-1899/1826.Faulty Sensor/README.md b/solution/1800-1899/1826.Faulty Sensor/README.md
index ef48efe0cfbb4..0ae247a90eb46 100644
--- a/solution/1800-1899/1826.Faulty Sensor/README.md
+++ b/solution/1800-1899/1826.Faulty Sensor/README.md
@@ -66,7 +66,7 @@
遍历结束,说明无法确定有缺陷的传感器,返回 $-1$。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。
+时间复杂度 $O(n)$,其中 $n$ 为数组长度。空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1826.Faulty Sensor/README_EN.md b/solution/1800-1899/1826.Faulty Sensor/README_EN.md
index a03441335471a..1b4924842c72e 100644
--- a/solution/1800-1899/1826.Faulty Sensor/README_EN.md
+++ b/solution/1800-1899/1826.Faulty Sensor/README_EN.md
@@ -53,6 +53,14 @@ The fourth data point from sensor 1 is dropped, and the last value of sensor 1 i
## Solutions
+**Solution 1: Traversal**
+
+Traverse both arrays, find the first unequal position $i$. If $i \lt n - 1$, loop to compare $sensor1[i + 1]$ and $sensor2[i]$, if they are not equal, it indicates that sensor $1$ is defective, return $1$; otherwise compare $sensor1[i]$ and $sensor2[i + 1]$, if they are not equal, it indicates that sensor $2$ is defective, return $2$.
+
+If the traversal ends, it means that the defective sensor cannot be determined, return $-1$.
+
+The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README.md b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README.md
index 2d25801b4b6ad..899537c064c96 100644
--- a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README.md
+++ b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README.md
@@ -59,7 +59,7 @@
从左到右遍历数组 `nums`,对于当前遍历到的元素 $v$,如果 $v \lt mx + 1$,那么我们需要将其增加到 $mx + 1$,这样才能保证数组严格递增。因此,我们此次需要进行的操作次数为 $max(0, mx + 1 - v)$,累加到答案中,然后更新 $mx=max(mx + 1, v)$。继续遍历下一个元素,直到遍历完整个数组。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。
+时间复杂度 $O(n)$,其中 $n$ 为数组 `nums` 的长度。空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md
index bdbbaff652bef..e091d69993010 100644
--- a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md
+++ b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md
@@ -50,6 +50,14 @@
## Solutions
+**Solution 1: Single Pass**
+
+We use a variable $mx$ to record the maximum value of the current strictly increasing array, initially $mx = 0$.
+
+Traverse the array `nums` from left to right. For the current element $v$, if $v \lt mx + 1$, we need to increase it to $mx + 1$ to ensure the array is strictly increasing. Therefore, the number of operations we need to perform this time is $max(0, mx + 1 - v)$, which is added to the answer, and then we update $mx=max(mx + 1, v)$. Continue to traverse the next element until the entire array is traversed.
+
+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/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md b/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md
index f2ba1e08c875f..01406f8334dec 100644
--- a/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md
+++ b/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md
@@ -50,6 +50,12 @@ queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is pu
## Solutions
+**Solution 1: Enumeration**
+
+Enumerate all the circles $(x, y, r)$. For each circle, calculate the number of points within the circle to get the answer.
+
+The time complexity is $O(m \times n)$, where $m$ and $n$ are the lengths of the arrays `queries` and `points` respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/README_EN.md b/solution/1800-1899/1829.Maximum XOR for Each Query/README_EN.md
index e68162d6670e2..364660b5f4766 100644
--- a/solution/1800-1899/1829.Maximum XOR for Each Query/README_EN.md
+++ b/solution/1800-1899/1829.Maximum XOR for Each Query/README_EN.md
@@ -58,6 +58,24 @@
## Solutions
+**Solution 1: Bitwise Operation + Enumeration**
+
+First, we preprocess the XOR sum $xs$ of the array `nums`, i.e., $xs=nums[0] \oplus nums[1] \oplus \cdots \oplus nums[n-1]$.
+
+Next, we enumerate each element $x$ in the array `nums` from back to front. The current XOR sum is $xs$. We need to find a number $k$ such that the value of $xs \oplus k$ is as large as possible, and $k \lt 2^{maximumBit}$.
+
+That is to say, we start from the $maximumBit - 1$ bit of $xs$ and enumerate to the lower bit. If a bit of $xs$ is $0$, then we set the corresponding bit of $k$ to $1$. Otherwise, we set the corresponding bit of $k$ to $0$. In this way, the final $k$ is the answer to each query. Then, we update $xs$ to $xs \oplus x$ and continue to enumerate the next element.
+
+The time complexity is $O(n \times m)$, where $n$ and $m$ are the values of the array `nums` and `maximumBit` respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$.
+
+**Solution 2: Enumeration Optimization**
+
+Similar to Solution 1, we first preprocess the XOR sum $xs$ of the array `nums`, i.e., $xs=nums[0] \oplus nums[1] \oplus \cdots \oplus nums[n-1]$.
+
+Next, we calculate $2^{maximumBit} - 1$, which is $2^{maximumBit}$ minus $1$, denoted as $mask$. Then, we enumerate each element $x$ in the array `nums` from back to front. The current XOR sum is $xs$, then $k=xs \oplus mask$ is the answer to each query. Then, we update $xs$ to $xs \oplus x$ and continue to enumerate the next element.
+
+The time complexity is $O(n)$, where $n$ is the length of the array `nums`. Ignoring the space consumption of the answer, the space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md b/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md
index 668f9dd22aa71..5ff0b7a4690bb 100644
--- a/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md
+++ b/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md
@@ -49,6 +49,22 @@ Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then rever
## Solutions
+**Solution 1: Counting + Permutation and Combination + Preprocessing**
+
+The operation in the problem is actually to find the previous permutation in lexicographical order of the current permutation. Therefore, we only need to find the number of permutations smaller than the current permutation, which is the answer.
+
+Here we need to consider a problem: given the frequency of each letter, how many different permutations can we construct?
+
+Suppose there are a total of $n$ letters, among which there are $n_1$ letters $a$, $n_2$ letters $b$, and $n_3$ letters $c$. Then we can construct $\frac{n!}{n_1! \times n_2! \times n_3!}$ different permutations. Where $n=n_1+n_2+n_3$.
+
+We can pre-calculate all factorials $f$ and the inverse of the factorials $g$ through preprocessing. The inverse of the factorial can be obtained through Fermat's little theorem.
+
+Next, we traverse the string $s$ from left to right. For each position $i$, we need to find out how many letters are smaller than $s[i]$, denoted as $m$. Then, we can construct $m \times \frac{(n - i - 1)!}{n_1! \times n_2! \cdots \times n_k!}$ different permutations, where $k$ is the number of types of letters, and add them to the answer. Next, we reduce the frequency of $s[i]$ by one and continue to traverse the next position.
+
+After traversing the entire string, we can get the answer. Note the modulo operation of the answer.
+
+The time complexity is $O(n \times k)$, and the space complexity is $O(n)$. Where $n$ and $k$ are the length of the string and the number of types of letters, respectively.
+
### **Python3**
diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/README.md b/solution/1800-1899/1832.Check if the Sentence Is Pangram/README.md
index b05ffb6e1b257..b6e525b41b318 100644
--- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/README.md
+++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/README.md
@@ -54,7 +54,7 @@
最后判断 $mask$ 的二进制表示中是否有 $26$ 个 $1$,也即判断 $mask$ 是否等于 $2^{26} - 1$。若是,返回 `true`,否则返回 `false`。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 `sentence` 的长度。
+时间复杂度 $O(n)$,其中 $n$ 为字符串 `sentence` 的长度。空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md b/solution/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md
index 47c1b44624817..f81fa8095fde3 100644
--- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md
+++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md
@@ -34,6 +34,20 @@
## Solutions
+**Solution 1: Array or Hash Table**
+
+Traverse the string `sentence`, use an array or hash table to record the letters that have appeared, and finally check whether there are $26$ letters in the array or hash table.
+
+The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string `sentence`, and $C$ is the size of the character set. In this problem, $C = 26$.
+
+**Solution 2: Bit Manipulation**
+
+We can also use an integer $mask$ to record the letters that have appeared, where the $i$-th bit of $mask$ indicates whether the $i$-th letter has appeared.
+
+Finally, check whether there are $26$ $1$s in the binary representation of $mask$, that is, check whether $mask$ is equal to $2^{26} - 1$. If so, return `true`, otherwise return `false`.
+
+The time complexity is $O(n)$, where $n$ is the length of the string `sentence`. The space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1834.Single-Threaded CPU/README_EN.md b/solution/1800-1899/1834.Single-Threaded CPU/README_EN.md
index 2e058081dbd44..aa0951d96024c 100644
--- a/solution/1800-1899/1834.Single-Threaded CPU/README_EN.md
+++ b/solution/1800-1899/1834.Single-Threaded CPU/README_EN.md
@@ -61,6 +61,20 @@
## Solutions
+**Solution 1: Sorting + Priority Queue (Min Heap)**
+
+First, we sort the tasks by `enqueueTime` in ascending order. Next, we use a priority queue (min heap) to maintain the currently executable tasks. The elements in the queue are `(processingTime, index)`, which represent the execution time and the index of the task. We also use a variable $t$ to represent the current time, initially set to $0$.
+
+Next, we simulate the execution process of the tasks.
+
+If the current queue is empty, it means there are no executable tasks at the moment. We update $t$ to the larger value between the `enqueueTime` of the next task and the current time $t$. Then, we add all tasks with `enqueueTime` less than or equal to $t$ to the queue.
+
+Then, we take out a task from the queue, add its index to the answer array, and update $t$ to the sum of the current time $t$ and the execution time of the current task.
+
+We repeat the above process until the queue is empty and all tasks have been added to the queue.
+
+The time complexity is $O(n \times \log n)$, where $n$ is the number of tasks.
+
### **Python3**
diff --git a/solution/1800-1899/1837.Sum of Digits in Base K/README_EN.md b/solution/1800-1899/1837.Sum of Digits in Base K/README_EN.md
index 4806290a2c202..dc8e8ed1072fb 100644
--- a/solution/1800-1899/1837.Sum of Digits in Base K/README_EN.md
+++ b/solution/1800-1899/1837.Sum of Digits in Base K/README_EN.md
@@ -35,6 +35,12 @@
## Solutions
+**Solution 1: Mathematics**
+
+We divide $n$ by $k$ and take the remainder until it is $0$. The sum of the remainders gives the result.
+
+The time complexity is $O(\log_{k}n)$, and the space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md b/solution/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md
index c4c9cb13ffadd..7f379cea68b3c 100644
--- a/solution/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md
+++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md
@@ -48,6 +48,24 @@ Explanation: Increment the first element three times and the second ele
## Solutions
+**Method 1: Sorting + Sliding Window**
+
+We can first sort the array $nums$, then enumerate each number as the most frequent element, and use a sliding window to maintain the number of operations to increase all numbers from index $l$ to $r$ to $nums[r]$. If the number of operations is greater than $k$, the left end of the window moves to the right until the number of operations is less than or equal to $k$. In this way, we can find out the maximum frequency for each number as the most frequent element.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array $nums$.
+
+**Method 2: Sorting + Prefix Sum + Binary Search**
+
+We observe that if a range length $cnt$ meets the condition, then the range length less than $cnt$ must also meet the condition. Therefore, we can use the method of binary search to find the maximum range length that meets the condition.
+
+Before binary search, we need to sort the array $nums[r]$, then calculate the prefix sum array $s$ of the array $nums[r]$, where $s[i]$ represents the sum of the first $i$ numbers in the array $nums[r]$. In this way, we can find the sum of the range $[i, j]$ is $s[j + 1] - s[i]$ in $O(1)$ time.
+
+Next, we define the left boundary of the binary search as $left=1$, $right=n$. Then we binary search the range length $mid$, if the current range length $mid$ meets the condition, then we update the left boundary of the binary search to $mid$, otherwise update the right boundary of the binary search to $mid-1$. Finally, we return the left boundary of the binary search.
+
+The problem is transformed into how to judge whether the range with length $cnt$ meets the condition. We enumerate the left endpoint $i$ in the range $[0,..n-cnt]$, then the right endpoint of the range at this time is $j = i + cnt - 1$. The number of operations required to increase all numbers in the range to $nums[j]$ is $nums[j] \times cnt - (s[j + 1] - s[i])$. If this number of operations is less than or equal to $k$, it means that the range with length $cnt$ meets the condition, return `true`. Otherwise, the enumeration ends, return `false`.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.
+
### **Python3**
diff --git a/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md b/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md
index bbfd3aeabb003..2f257483cfee0 100644
--- a/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md
+++ b/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md
@@ -51,6 +51,14 @@
## Solutions
+**Solution 1: Two Pointers + Simulation**
+
+We can first transform the string `word`. For example, for `word="aaaeiouu"`, we can transform it into data items `('a', 3)`, `('e', 1)`, `('i', 1)`, `('o', 1)`, `('u', 2)` and store them in an array `arr`. Each data item's first element represents a vowel, and the second element represents the number of times the vowel appears consecutively. This transformation can be implemented using two pointers.
+
+Next, we traverse the array `arr`, each time taking $5$ adjacent data items, and judge whether the vowels in these data items are `'a'`, `'e'`, `'i'`, `'o'`, `'u'` respectively. If so, calculate the total number of times the vowels appear in these $5$ data items, which is the length of the current beautiful substring, and update the maximum value of the answer.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string `word`.
+
### **Python3**
diff --git a/solution/1800-1899/1840.Maximum Building Height/README.md b/solution/1800-1899/1840.Maximum Building Height/README.md
index 3822483cbe52b..a690b5b0746cd 100644
--- a/solution/1800-1899/1840.Maximum Building Height/README.md
+++ b/solution/1800-1899/1840.Maximum Building Height/README.md
@@ -70,9 +70,9 @@
首先,我们将所有的限制条件按照建筑物的编号从小到大排序。
-然后我们从左到右遍历所有的限制条件,对于每个限制条件,我们可以得到一个最高高度的上界,即 $r_i[1] = min(r_i[1], r_{i-1}[1] + r_i[0] - r_{i-1}[0])$,其中 $r_i$ 表示第 $i$ 个限制条件,而 $r_i[0]$ 和 $r_i[1]$ 分别表示建筑物的编号以及建筑物的最高高度的上界。
+然后我们从左到右遍历所有的限制条件,对于每个限制条件,我们可以得到一个最高高度的上界,即 $r_i[1] = \min(r_i[1], r_{i-1}[1] + r_i[0] - r_{i-1}[0])$,其中 $r_i$ 表示第 $i$ 个限制条件,而 $r_i[0]$ 和 $r_i[1]$ 分别表示建筑物的编号以及建筑物的最高高度的上界。
-然后我们从右到左遍历所有的限制条件,对于每个限制条件,我们可以得到一个最高高度的上界,即 $r_i[1] = min(r_i[1], r_{i+1}[1] + r_{i+1}[0] - r_i[0])$。
+然后我们从右到左遍历所有的限制条件,对于每个限制条件,我们可以得到一个最高高度的上界,即 $r_i[1] = \min(r_i[1], r_{i+1}[1] + r_{i+1}[0] - r_i[0])$。
这样,我们就得到了每个限制建筑物的最高高度的上界。
diff --git a/solution/1800-1899/1840.Maximum Building Height/README_EN.md b/solution/1800-1899/1840.Maximum Building Height/README_EN.md
index 0a201372b075b..f9c4795d88bb5 100644
--- a/solution/1800-1899/1840.Maximum Building Height/README_EN.md
+++ b/solution/1800-1899/1840.Maximum Building Height/README_EN.md
@@ -60,6 +60,20 @@ We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest b
## Solutions
+**Soution 1: Sorting + Mathematics**
+
+First, we sort all the restrictions by the building number in ascending order.
+
+Then we traverse all the restrictions from left to right. For each restriction, we can get an upper bound of the maximum height, that is, $r_i[1] = \min(r_i[1], r_{i-1}[1] + r_i[0] - r_{i-1}[0])$, where $r_i$ represents the $i$-th restriction, and $r_i[0]$ and $r_i[1]$ represent the building number and the upper bound of the maximum height of the building, respectively.
+
+Then we traverse all the restrictions from right to left. For each restriction, we can get an upper bound of the maximum height, that is, $r_i[1] = \min(r_i[1], r_{i+1}[1] + r_{i+1}[0] - r_i[0])$.
+
+In this way, we get the upper bound of the maximum height for each restricted building.
+
+The problem asks for the height of the tallest building. We can enumerate the buildings $i$ and $i+1$ between two adjacent restrictions. To maximize the height, the height should first increase and then decrease. Suppose the maximum height is $t$, then $t - r_i[1] + t - r_{i+1}[1] \leq r_{i+1}[0] - r_i[0]$, that is, $t \leq \frac{r_i[1] + r_{i+1}[1] + r_{i+1}[0] - r_{i}[0]}{2}$. We can take the maximum value among all $t$.
+
+The time complexity is $O(m \times \log m)$, and the space complexity is $O(m)$. Where $m$ is the number of restrictions.
+
### **Python3**
diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/README.md b/solution/1800-1899/1842.Next Palindrome Using Same Digits/README.md
index f47434daeb281..202179c5c907b 100644
--- a/solution/1800-1899/1842.Next Palindrome Using Same Digits/README.md
+++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/README.md
@@ -51,6 +51,12 @@
+**方法一:求前一半的下一个排列**
+
+根据题目描述,我们只需要求出前一半的下一个排列,然后遍历前一半,对称赋值后半部分即可。
+
+时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。
+
### **Python3**
@@ -58,7 +64,29 @@
```python
-
+class Solution:
+ def nextPalindrome(self, num: str) -> str:
+ def next_permutation(nums: List[str]) -> bool:
+ n = len(nums) // 2
+ i = n - 2
+ while i >= 0 and nums[i] >= nums[i + 1]:
+ i -= 1
+ if i < 0:
+ return False
+ j = n - 1
+ while j >= 0 and nums[j] <= nums[i]:
+ j -= 1
+ nums[i], nums[j] = nums[j], nums[i]
+ nums[i + 1 : n] = nums[i + 1 : n][::-1]
+ return True
+
+ nums = list(num)
+ if not next_permutation(nums):
+ return ""
+ n = len(nums)
+ for i in range(n // 2):
+ nums[n - i - 1] = nums[i]
+ return "".join(nums)
```
### **Java**
@@ -66,7 +94,137 @@
```java
+class Solution {
+ public String nextPalindrome(String num) {
+ char[] nums = num.toCharArray();
+ if (!nextPermutation(nums)) {
+ return "";
+ }
+ int n = nums.length;
+ for (int i = 0; i < n / 2; ++i) {
+ nums[n - 1 - i] = nums[i];
+ }
+ return String.valueOf(nums);
+ }
+
+ private boolean nextPermutation(char[] nums) {
+ int n = nums.length / 2;
+ int i = n - 2;
+ while (i >= 0 && nums[i] >= nums[i + 1]) {
+ --i;
+ }
+ if (i < 0) {
+ return false;
+ }
+ int j = n - 1;
+ while (j >= 0 && nums[i] >= nums[j]) {
+ --j;
+ }
+ swap(nums, i++, j);
+ for (j = n - 1; i < j; ++i, --j) {
+ swap(nums, i, j);
+ }
+ return true;
+ }
+
+ private void swap(char[] nums, int i, int j) {
+ char t = nums[i];
+ nums[i] = nums[j];
+ nums[j] = t;
+ }
+}
+```
+
+### **C++**
+
+```cpp
+class Solution {
+public:
+ string nextPalindrome(string num) {
+ int n = num.size();
+ string nums = num.substr(0, n / 2);
+ if (!next_permutation(begin(nums), end(nums))) {
+ return "";
+ }
+ for (int i = 0; i < n / 2; ++i) {
+ num[i] = nums[i];
+ num[n - i - 1] = nums[i];
+ }
+ return num;
+ }
+};
+```
+
+### **Go**
+
+```go
+func nextPalindrome(num string) string {
+ nums := []byte(num)
+ n := len(nums)
+ if !nextPermutation(nums) {
+ return ""
+ }
+ for i := 0; i < n/2; i++ {
+ nums[n-1-i] = nums[i]
+ }
+ return string(nums)
+}
+
+func nextPermutation(nums []byte) bool {
+ n := len(nums) / 2
+ i := n - 2
+ for i >= 0 && nums[i] >= nums[i+1] {
+ i--
+ }
+ if i < 0 {
+ return false
+ }
+ j := n - 1
+ for j >= 0 && nums[j] <= nums[i] {
+ j--
+ }
+ nums[i], nums[j] = nums[j], nums[i]
+ for i, j = i+1, n-1; i < j; i, j = i+1, j-1 {
+ nums[i], nums[j] = nums[j], nums[i]
+ }
+ return true
+}
+```
+### **TypeScript**
+
+```ts
+function nextPalindrome(num: string): string {
+ const nums = num.split('');
+ const n = nums.length;
+ if (!nextPermutation(nums)) {
+ return '';
+ }
+ for (let i = 0; i < n >> 1; ++i) {
+ nums[n - 1 - i] = nums[i];
+ }
+ return nums.join('');
+}
+
+function nextPermutation(nums: string[]): boolean {
+ const n = nums.length >> 1;
+ let i = n - 2;
+ while (i >= 0 && nums[i] >= nums[i + 1]) {
+ i--;
+ }
+ if (i < 0) {
+ return false;
+ }
+ let j = n - 1;
+ while (j >= 0 && nums[i] >= nums[j]) {
+ j--;
+ }
+ [nums[i], nums[j]] = [nums[j], nums[i]];
+ for (i = i + 1, j = n - 1; i < j; ++i, --j) {
+ [nums[i], nums[j]] = [nums[j], nums[i]];
+ }
+ return true;
+}
```
### **...**
diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md b/solution/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md
index 34c6f7866e807..8c44f4dd9e8a6 100644
--- a/solution/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md
+++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md
@@ -45,18 +45,176 @@
## Solutions
+**Solution 1: Find the Next Permutation of the First Half**
+
+According to the problem description, we only need to find the next permutation of the first half of the string, then traverse the first half and symmetrically assign values to the second half.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string.
+
### **Python3**
```python
-
+class Solution:
+ def nextPalindrome(self, num: str) -> str:
+ def next_permutation(nums: List[str]) -> bool:
+ n = len(nums) // 2
+ i = n - 2
+ while i >= 0 and nums[i] >= nums[i + 1]:
+ i -= 1
+ if i < 0:
+ return False
+ j = n - 1
+ while j >= 0 and nums[j] <= nums[i]:
+ j -= 1
+ nums[i], nums[j] = nums[j], nums[i]
+ nums[i + 1 : n] = nums[i + 1 : n][::-1]
+ return True
+
+ nums = list(num)
+ if not next_permutation(nums):
+ return ""
+ n = len(nums)
+ for i in range(n // 2):
+ nums[n - i - 1] = nums[i]
+ return "".join(nums)
```
### **Java**
```java
+class Solution {
+ public String nextPalindrome(String num) {
+ char[] nums = num.toCharArray();
+ if (!nextPermutation(nums)) {
+ return "";
+ }
+ int n = nums.length;
+ for (int i = 0; i < n / 2; ++i) {
+ nums[n - 1 - i] = nums[i];
+ }
+ return String.valueOf(nums);
+ }
+
+ private boolean nextPermutation(char[] nums) {
+ int n = nums.length / 2;
+ int i = n - 2;
+ while (i >= 0 && nums[i] >= nums[i + 1]) {
+ --i;
+ }
+ if (i < 0) {
+ return false;
+ }
+ int j = n - 1;
+ while (j >= 0 && nums[i] >= nums[j]) {
+ --j;
+ }
+ swap(nums, i++, j);
+ for (j = n - 1; i < j; ++i, --j) {
+ swap(nums, i, j);
+ }
+ return true;
+ }
+
+ private void swap(char[] nums, int i, int j) {
+ char t = nums[i];
+ nums[i] = nums[j];
+ nums[j] = t;
+ }
+}
+```
+
+### **C++**
+
+```cpp
+class Solution {
+public:
+ string nextPalindrome(string num) {
+ int n = num.size();
+ string nums = num.substr(0, n / 2);
+ if (!next_permutation(begin(nums), end(nums))) {
+ return "";
+ }
+ for (int i = 0; i < n / 2; ++i) {
+ num[i] = nums[i];
+ num[n - i - 1] = nums[i];
+ }
+ return num;
+ }
+};
+```
+
+### **Go**
+
+```go
+func nextPalindrome(num string) string {
+ nums := []byte(num)
+ n := len(nums)
+ if !nextPermutation(nums) {
+ return ""
+ }
+ for i := 0; i < n/2; i++ {
+ nums[n-1-i] = nums[i]
+ }
+ return string(nums)
+}
+
+func nextPermutation(nums []byte) bool {
+ n := len(nums) / 2
+ i := n - 2
+ for i >= 0 && nums[i] >= nums[i+1] {
+ i--
+ }
+ if i < 0 {
+ return false
+ }
+ j := n - 1
+ for j >= 0 && nums[j] <= nums[i] {
+ j--
+ }
+ nums[i], nums[j] = nums[j], nums[i]
+ for i, j = i+1, n-1; i < j; i, j = i+1, j-1 {
+ nums[i], nums[j] = nums[j], nums[i]
+ }
+ return true
+}
+```
+### **TypeScript**
+
+```ts
+function nextPalindrome(num: string): string {
+ const nums = num.split('');
+ const n = nums.length;
+ if (!nextPermutation(nums)) {
+ return '';
+ }
+ for (let i = 0; i < n >> 1; ++i) {
+ nums[n - 1 - i] = nums[i];
+ }
+ return nums.join('');
+}
+
+function nextPermutation(nums: string[]): boolean {
+ const n = nums.length >> 1;
+ let i = n - 2;
+ while (i >= 0 && nums[i] >= nums[i + 1]) {
+ i--;
+ }
+ if (i < 0) {
+ return false;
+ }
+ let j = n - 1;
+ while (j >= 0 && nums[i] >= nums[j]) {
+ j--;
+ }
+ [nums[i], nums[j]] = [nums[j], nums[i]];
+ for (i = i + 1, j = n - 1; i < j; ++i, --j) {
+ [nums[i], nums[j]] = [nums[j], nums[i]];
+ }
+ return true;
+}
```
### **...**
diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.cpp b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.cpp
new file mode 100644
index 0000000000000..90cd4d6a6c389
--- /dev/null
+++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.cpp
@@ -0,0 +1,15 @@
+class Solution {
+public:
+ string nextPalindrome(string num) {
+ int n = num.size();
+ string nums = num.substr(0, n / 2);
+ if (!next_permutation(begin(nums), end(nums))) {
+ return "";
+ }
+ for (int i = 0; i < n / 2; ++i) {
+ num[i] = nums[i];
+ num[n - i - 1] = nums[i];
+ }
+ return num;
+ }
+};
\ No newline at end of file
diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.go b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.go
new file mode 100644
index 0000000000000..e9bc199395ddd
--- /dev/null
+++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.go
@@ -0,0 +1,31 @@
+func nextPalindrome(num string) string {
+ nums := []byte(num)
+ n := len(nums)
+ if !nextPermutation(nums) {
+ return ""
+ }
+ for i := 0; i < n/2; i++ {
+ nums[n-1-i] = nums[i]
+ }
+ return string(nums)
+}
+
+func nextPermutation(nums []byte) bool {
+ n := len(nums) / 2
+ i := n - 2
+ for i >= 0 && nums[i] >= nums[i+1] {
+ i--
+ }
+ if i < 0 {
+ return false
+ }
+ j := n - 1
+ for j >= 0 && nums[j] <= nums[i] {
+ j--
+ }
+ nums[i], nums[j] = nums[j], nums[i]
+ for i, j = i+1, n-1; i < j; i, j = i+1, j-1 {
+ nums[i], nums[j] = nums[j], nums[i]
+ }
+ return true
+}
\ No newline at end of file
diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.java b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.java
new file mode 100644
index 0000000000000..b2abe6bbff2e3
--- /dev/null
+++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.java
@@ -0,0 +1,39 @@
+class Solution {
+ public String nextPalindrome(String num) {
+ char[] nums = num.toCharArray();
+ if (!nextPermutation(nums)) {
+ return "";
+ }
+ int n = nums.length;
+ for (int i = 0; i < n / 2; ++i) {
+ nums[n - 1 - i] = nums[i];
+ }
+ return String.valueOf(nums);
+ }
+
+ private boolean nextPermutation(char[] nums) {
+ int n = nums.length / 2;
+ int i = n - 2;
+ while (i >= 0 && nums[i] >= nums[i + 1]) {
+ --i;
+ }
+ if (i < 0) {
+ return false;
+ }
+ int j = n - 1;
+ while (j >= 0 && nums[i] >= nums[j]) {
+ --j;
+ }
+ swap(nums, i++, j);
+ for (j = n - 1; i < j; ++i, --j) {
+ swap(nums, i, j);
+ }
+ return true;
+ }
+
+ private void swap(char[] nums, int i, int j) {
+ char t = nums[i];
+ nums[i] = nums[j];
+ nums[j] = t;
+ }
+}
\ No newline at end of file
diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.py b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.py
new file mode 100644
index 0000000000000..a555ffdf7a0e9
--- /dev/null
+++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.py
@@ -0,0 +1,23 @@
+class Solution:
+ def nextPalindrome(self, num: str) -> str:
+ def next_permutation(nums: List[str]) -> bool:
+ n = len(nums) // 2
+ i = n - 2
+ while i >= 0 and nums[i] >= nums[i + 1]:
+ i -= 1
+ if i < 0:
+ return False
+ j = n - 1
+ while j >= 0 and nums[j] <= nums[i]:
+ j -= 1
+ nums[i], nums[j] = nums[j], nums[i]
+ nums[i + 1 : n] = nums[i + 1 : n][::-1]
+ return True
+
+ nums = list(num)
+ if not next_permutation(nums):
+ return ""
+ n = len(nums)
+ for i in range(n // 2):
+ nums[n - i - 1] = nums[i]
+ return "".join(nums)
diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.ts b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.ts
new file mode 100644
index 0000000000000..3639a33d59a95
--- /dev/null
+++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/Solution.ts
@@ -0,0 +1,31 @@
+function nextPalindrome(num: string): string {
+ const nums = num.split('');
+ const n = nums.length;
+ if (!nextPermutation(nums)) {
+ return '';
+ }
+ for (let i = 0; i < n >> 1; ++i) {
+ nums[n - 1 - i] = nums[i];
+ }
+ return nums.join('');
+}
+
+function nextPermutation(nums: string[]): boolean {
+ const n = nums.length >> 1;
+ let i = n - 2;
+ while (i >= 0 && nums[i] >= nums[i + 1]) {
+ i--;
+ }
+ if (i < 0) {
+ return false;
+ }
+ let j = n - 1;
+ while (j >= 0 && nums[i] >= nums[j]) {
+ j--;
+ }
+ [nums[i], nums[j]] = [nums[j], nums[i]];
+ for (i = i + 1, j = n - 1; i < j; ++i, --j) {
+ [nums[i], nums[j]] = [nums[j], nums[i]];
+ }
+ return true;
+}
diff --git a/solution/1800-1899/1844.Replace All Digits with Characters/README_EN.md b/solution/1800-1899/1844.Replace All Digits with Characters/README_EN.md
index 482ad411ff226..7b7aa83ce56dd 100644
--- a/solution/1800-1899/1844.Replace All Digits with Characters/README_EN.md
+++ b/solution/1800-1899/1844.Replace All Digits with Characters/README_EN.md
@@ -49,6 +49,14 @@
## Solutions
+**Solution 1: Simulation**
+
+Traverse the string, for characters at odd indices, replace them with the character that is a certain number of positions after the previous character.
+
+Finally, return the replaced string.
+
+The time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignoring the space consumption of the answer, the space complexity is $O(1)$.
+
### **Python3**
diff --git a/solution/1800-1899/1845.Seat Reservation Manager/README_EN.md b/solution/1800-1899/1845.Seat Reservation Manager/README_EN.md
index 84ced81b35ea8..f83ba80bf6162 100644
--- a/solution/1800-1899/1845.Seat Reservation Manager/README_EN.md
+++ b/solution/1800-1899/1845.Seat Reservation Manager/README_EN.md
@@ -49,6 +49,18 @@ seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5
## Solutions
+**Solution 1: Priority Queue (Min Heap)**
+
+We can use a priority queue (min heap) to maintain the smallest number of reservable seats.
+
+Initially, put all seat numbers into the priority queue.
+
+When the `reserve` method is called, take out the smallest number from the priority queue, which is the smallest number of reservable seats.
+
+When the `unreserve` method is called, put the seat number back into the priority queue.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of seats.
+
### **Python3**
diff --git a/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README.md b/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README.md
index f57fadf4cd3e6..58248789592c8 100644
--- a/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README.md
+++ b/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README.md
@@ -71,6 +71,14 @@ arr 中最大元素为 3 。
**方法一:排序 + 贪心**
+我们先对数组进行排序,然后将数组的第一个元素设置为 $1$。
+
+接下来,我们从第二个元素开始遍历数组,如果当前元素与前一个元素的差值大于 $1$,我们就贪心地将当前元素减小为前一个元素加 $1$。
+
+最后,我们返回数组中的最大元素。
+
+时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组长度。
+
### **Python3**
diff --git a/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md b/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md
index 45a12da337e3f..729f297ebf90e 100644
--- a/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md
+++ b/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md
@@ -63,6 +63,16 @@ The largest element in arr is 3.
## Solutions
+**Solution 1: Sorting + Greedy Algorithm**
+
+First, we sort the array and then set the first element of the array to $1$.
+
+Next, we start traversing the array from the second element. If the difference between the current element and the previous one is more than $1$, we greedily reduce the current element to the previous element plus $1$.
+
+Finally, we return the maximum element in the array.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array.
+
### **Python3**
diff --git a/solution/1800-1899/1847.Closest Room/README_EN.md b/solution/1800-1899/1847.Closest Room/README_EN.md
index ae8f2c1236270..63671490189ee 100644
--- a/solution/1800-1899/1847.Closest Room/README_EN.md
+++ b/solution/1800-1899/1847.Closest Room/README_EN.md
@@ -52,6 +52,16 @@ Query = [2,5]: Room number 3 is the only room with a size of at least 5. The ans
## Solutions
+**Solution 1: Offline Query + Ordered Set + Binary Search**
+
+We notice that the order of queries does not affect the answer, and the problem involves the size relationship of room areas. Therefore, we can sort the queries in ascending order of minimum area, so that we can process each query from small to large. Also, we sort the rooms in ascending order of area.
+
+Next, we create an ordered list and add all room numbers to the ordered list.
+
+Then, we process each query from small to large. For each query, we first remove all rooms with an area less than or equal to the current query's minimum area from the ordered list. Then, in the remaining rooms, we use binary search to find the room number closest to the current query. If there is no such room, we return $-1$.
+
+The time complexity is $O(n \times \log n + k \times \log k)$, and the space complexity is $O(n + k)$. Where $n$ and $k$ are the number of rooms and queries, respectively.
+
### **Python3**
diff --git a/solution/1800-1899/1848.Minimum Distance to the Target Element/README.md b/solution/1800-1899/1848.Minimum Distance to the Target Element/README.md
index 52305ca29720c..3af348d734023 100644
--- a/solution/1800-1899/1848.Minimum Distance to the Target Element/README.md
+++ b/solution/1800-1899/1848.Minimum Distance to the Target Element/README.md
@@ -55,9 +55,9 @@
**方法一:一次遍历**
-遍历数组,找到所有等于 `target` 的下标,然后计算 `abs(i - start)`,取最小值即可。
+遍历数组,找到所有等于 $target$ 的下标,然后计算 $|i - start|$,取最小值即可。
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。
+时间复杂度 $O(n)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md b/solution/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md
index 4c98fb96e0d41..4b698a8ee4fb8 100644
--- a/solution/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md
+++ b/solution/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md
@@ -47,6 +47,12 @@
## Solutions
+**Solution 1: Single Pass**
+
+Traverse the array, find all indices equal to $target$, then calculate $|i - start|$, and take the minimum value.
+
+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/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md
index d6ed7b9b34677..cbfee9331af28 100644
--- a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md
+++ b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md
@@ -53,6 +53,12 @@ The values are in descending order with adjacent values differing by 1.
## Solutions
+**Solution 1: DFS (Depth-First Search)**
+
+Starting from the first character of the string, enumerate all possible split positions. Check if the split substring meets the requirements of the problem. If it does, continue to recursively check whether the remaining substring meets the requirements, until the entire string is traversed.
+
+The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the string.
+
### **Python3**
diff --git a/solution/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md b/solution/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md
index ad94015619a2b..2fa6984e19e21 100644
--- a/solution/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md
+++ b/solution/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md
@@ -48,6 +48,22 @@
## Solutions
+**Solution 1: Sorting + Offline Query + Priority Queue (Min Heap)**
+
+We notice that the order of queries does not affect the answer, and the intervals involved do not change. Therefore, we consider sorting all queries in ascending order, and sorting all intervals in ascending order of the left endpoint.
+
+We use a priority queue (min heap) $pq$ to maintain all current intervals. Each element in the queue is a pair $(v, r)$, representing an interval with length $v$ and right endpoint $r$. Initially, the priority queue is empty. In addition, we define a pointer $i$ that points to the current interval being traversed, and initially $i=0$.
+
+We traverse each query $(x, j)$ in ascending order and perform the following operations:
+
+- If the pointer $i$ has not traversed all intervals, and the left endpoint of the current interval $[a, b]$ is less than or equal to $x$, then we add this interval to the priority queue and move the pointer $i$ one step forward. Repeat this process.
+- If the priority queue is not empty, and the right endpoint of the heap top element is less than $x$, then we pop the heap top element. Repeat this process.
+- At this point, if the priority queue is not empty, then the heap top element is the smallest interval containing $x$. We add its length $v$ to the answer array $ans$.
+
+After the above process is over, we return the answer array $ans$.
+
+The time complexity is $O(n \times \log n + m \times \log m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the lengths of the arrays `intervals` and `queries` respectively.
+
### **Python3**
diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md
index e6d38ed43aa25..bd1875f8897c3 100644
--- a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md
+++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md
@@ -44,6 +44,12 @@
## Solutions
+**Solution 1: Sliding Window + Hash Table/Array**
+
+Use an array or hash table to record the occurrence of numbers in each subarray of size $k$. Then traverse the array, update the hash table each time, and record the number of types of numbers in the current window.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array.
+
### **Python3**
diff --git a/solution/1800-1899/1854.Maximum Population Year/README_EN.md b/solution/1800-1899/1854.Maximum Population Year/README_EN.md
index 1bb8aa8f90570..eaead5e298fb6 100644
--- a/solution/1800-1899/1854.Maximum Population Year/README_EN.md
+++ b/solution/1800-1899/1854.Maximum Population Year/README_EN.md
@@ -38,6 +38,14 @@ The earlier year between them is 1960.
## Solutions
+**Solution 1: Difference Array**
+
+We notice that the range of years is $[1950,..2050]$. Therefore, we can map these years to an array $d$ of length $101$, where the index of the array represents the value of the year minus $1950$.
+
+Next, we traverse $logs$. For each person, we increment $d[birth_i - 1950]$ by $1$ and decrement $d[death_i - 1950]$ by $1$. Finally, we traverse the array $d$, find the maximum value of the prefix sum, which is the year with the most population, and add $1950$ to get the answer.
+
+The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the array $logs$, and $C$ is the range size of the years, i.e., $2050 - 1950 + 1 = 101$.
+
### **Python3**
diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README.md b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README.md
index f2d942b28438e..ebb5f2c30ba77 100644
--- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README.md
+++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README.md
@@ -59,17 +59,17 @@
**方法一:二分查找**
-假设 `nums1`、`nums2` 的长度分别为 $m$ 和 $n$。
+假设 $nums1$, $nums2$ 的长度分别为 $m$ 和 $n$。
-遍历数组 `nums1`,对于每个数字 `nums1[i]`,二分查找 `nums2` 在 $[i,n)$ 范围内的数字,找到**最后一个**大于等于 `nums1[i]` 的位置 $j$,计算此位置与 $i$ 的距离,并更新最大距离值 `ans`。
+遍历数组 $nums1$,对于每个数字 $nums1[i]$,二分查找 $nums2$ 在 $[i,n)$ 范围内的数字,找到**最后一个**大于等于 $nums1[i]$ 的位置 $j$,计算此位置与 $i$ 的距离,并更新最大距离值 $ans$。
-时间复杂度 $O(m\log n)$,其中 $m$ 和 $n$ 分别为 `nums1` 和 `nums2` 的长度。
+时间复杂度 $O(m \times \log n)$,其中 $m$ 和 $n$ 分别为 $nums1$ 和 $nums2$ 的长度。空间复杂度 $O(1)$。
**方法二:双指针**
-在方法一中,我们只利用到 `nums2` 是非递增数组这一条件,实际上,`nums1` 也是非递增数组,我们可以用双指针 $i$ 和 $j$ 来遍历 `nums1` 和 `nums2`。
+在方法一中,我们只利用到 $nums2$ 是非递增数组这一条件,实际上,$nums1$ 也是非递增数组,我们可以用双指针 $i$ 和 $j$ 来遍历 $nums1$ 和 $nums2$。
-时间复杂度 $O(m+n)$。
+时间复杂度 $O(m+n)$,其中 $m$ 和 $n$ 分别为 $nums1$ 和 $nums2$ 的长度。空间复杂度 $O(1)$。
diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md
index c1f20700deca8..2a15ee4b03de0 100644
--- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md
+++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md
@@ -51,7 +51,13 @@ The maximum distance is 2 with pair (2,4).
## Solutions
-Binary search.
+**Solution 1: Binary Search**
+
+Assume the lengths of $nums1$ and $nums2$ are $m$ and $n$ respectively.
+
+Traverse array $nums1$, for each number $nums1[i]$, perform a binary search for numbers in $nums2$ in the range $[i,n)$, find the **last** position $j$ that is greater than or equal to $nums1[i]$, calculate the distance between this position and $i$, and update the maximum distance value $ans$.
+
+The time complexity is $O(m \times \log n)$, where $m$ and $n$ are the lengths of $nums1$ and $nums2$ respectively. The space complexity is $O(1)$.
diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md b/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md
index f2f4329883e2e..ebb444cc0da7e 100644
--- a/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md
+++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md
@@ -54,6 +54,16 @@
## Solutions
+**Solution 1: Monotonic Stack + Prefix Sum**
+
+We can enumerate each element $nums[i]$ as the minimum value of the subarray, and find the left and right boundaries $left[i]$ and $right[i]$ of the subarray. Where $left[i]$ represents the first position strictly less than $nums[i]$ on the left side of $i$, and $right[i]$ represents the first position less than or equal to $nums[i]$ on the right side of $i$.
+
+To conveniently calculate the sum of the subarray, we can preprocess the prefix sum array $s$, where $s[i]$ represents the sum of the first $i$ elements of $nums$.
+
+Then the minimum product with $nums[i]$ as the minimum value of the subarray is $nums[i] \times (s[right[i]] - s[left[i] + 1])$. We can enumerate each element $nums[i]$, find the minimum product with $nums[i]$ as the minimum value of the subarray, and then take the maximum value.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.
+
### **Python3**
diff --git a/solution/1800-1899/1859.Sorting the Sentence/README.md b/solution/1800-1899/1859.Sorting the Sentence/README.md
index 21f5217a49229..7958fa6aa2971 100644
--- a/solution/1800-1899/1859.Sorting the Sentence/README.md
+++ b/solution/1800-1899/1859.Sorting the Sentence/README.md
@@ -51,11 +51,13 @@
**方法一:字符串分割**
-先将字符串 `s` 按照空格分割,得到字符串数组 `words`。
+我们先将字符串 $s$ 按照空格分割,得到字符串数组 $words$。然后,我们创建一个长度为 $|words|$ 的字符串数组 $ans$,用于存放答案。
-遍历字符串数组 `words`,提取 `words[i]` 中最后一位字符,将其转换为数字,得到 `words[i][0:len(words[i])-1]` 的实际位置。
+接下来,遍历字符串数组 $words$ 中的每个字符串 $w$,找到 $w$ 的最后一个字符表示的位置 $i$,然后将 $w$ 的前 $|w|-1$ 个字符作为新的字符串 $w'$,将 $w'$ 放在数组 $ans$ 的第 $i$ 个位置。
-时间复杂度 $O(n)$,其中 $n$ 是字符串长度。
+最后,将数组 $ans$ 按照空格连接成字符串,即为答案。
+
+时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。
@@ -66,11 +68,18 @@
```python
class Solution:
def sortSentence(self, s: str) -> str:
- words = s.split()
- ans = [None] * len(words)
- for w in words:
- i = int(w[-1]) - 1
- ans[i] = w[:-1]
+ ws = [(w[:-1], int(w[-1])) for w in s.split()]
+ ws.sort(key=lambda x: x[1])
+ return ' '.join(w for w, _ in ws)
+```
+
+```python
+class Solution:
+ def sortSentence(self, s: str) -> str:
+ ws = s.split()
+ ans = [None] * len(ws)
+ for w in ws:
+ ans[int(w[-1]) - 1] = w[:-1]
return ' '.join(ans)
```
@@ -81,11 +90,12 @@ class Solution:
```java
class Solution {
public String sortSentence(String s) {
- String[] words = s.split(" ");
- String[] ans = new String[words.length];
- for (String w : words) {
- int i = w.charAt(w.length() - 1) - '1';
- ans[i] = w.substring(0, w.length() - 1);
+ String[] ws = s.split(" ");
+ int n = ws.length;
+ String[] ans = new String[n];
+ for (int i = 0; i < n; ++i) {
+ String w = ws[i];
+ ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1);
}
return String.join(" ", ans);
}
@@ -98,17 +108,18 @@ class Solution {
class Solution {
public:
string sortSentence(string s) {
- istringstream is(s);
- string t;
- vector words;
- while (is >> t) words.push_back(t);
- vector res(words.size());
- for (auto& w : words) {
- int i = w[w.size() - 1] - '1';
- res[i] = w.substr(0, w.size() - 1);
+ istringstream iss(s);
+ string w;
+ vector ws;
+ while (iss >> w) {
+ ws.push_back(w);
+ }
+ vector ss(ws.size());
+ for (auto& w : ws) {
+ ss[w.back() - '1'] = w.substr(0, w.size() - 1);
}
string ans;
- for (auto& w : res) {
+ for (auto& w : ss) {
ans += w + " ";
}
ans.pop_back();
@@ -121,11 +132,10 @@ public:
```go
func sortSentence(s string) string {
- words := strings.Split(s, " ")
- ans := make([]string, len(words))
- for _, w := range words {
- i := w[len(w)-1] - '1'
- ans[i] = w[:len(w)-1]
+ ws := strings.Split(s, " ")
+ ans := make([]string, len(ws))
+ for _, w := range ws {
+ ans[w[len(w)-1]-'1'] = w[:len(w)-1]
}
return strings.Join(ans, " ")
}
@@ -139,11 +149,10 @@ func sortSentence(s string) string {
* @return {string}
*/
var sortSentence = function (s) {
- const words = s.split(' ');
- const ans = new Array(words.length);
- for (const w of words) {
- const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0);
- ans[i] = w.slice(0, w.length - 1);
+ const ws = s.split(' ');
+ const ans = Array(ws.length);
+ for (const w of ws) {
+ ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1);
}
return ans.join(' ');
};
@@ -153,11 +162,10 @@ var sortSentence = function (s) {
```ts
function sortSentence(s: string): string {
- const words = s.split(' ');
- const ans = new Array(words.length);
- for (const w of words) {
- const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0);
- ans[i] = w.slice(0, w.length - 1);
+ const ws = s.split(' ');
+ const ans = Array(ws.length);
+ for (const w of ws) {
+ ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1);
}
return ans.join(' ');
}
diff --git a/solution/1800-1899/1859.Sorting the Sentence/README_EN.md b/solution/1800-1899/1859.Sorting the Sentence/README_EN.md
index def90c540ee4c..0b57e23b45781 100644
--- a/solution/1800-1899/1859.Sorting the Sentence/README_EN.md
+++ b/solution/1800-1899/1859.Sorting the Sentence/README_EN.md
@@ -44,6 +44,16 @@
## Solutions
+**Solution 1: String Splitting**
+
+First, we split the string $s$ by spaces to get the string array $words$. Then, we create a string array $ans$ of length $|words|$ to store the answer.
+
+Next, we iterate over each string $w$ in the string array $words$, find the position $i$ represented by the last character of $w$, then take the first $|w|-1$ characters of $w$ as the new string $w'$, and place $w'$ in the $i$th position of the array $ans$.
+
+Finally, we join the array $ans$ into a string by spaces, which is the answer.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$.
+
### **Python3**
@@ -51,11 +61,18 @@
```python
class Solution:
def sortSentence(self, s: str) -> str:
- words = s.split()
- ans = [None] * len(words)
- for w in words:
- i = int(w[-1]) - 1
- ans[i] = w[:-1]
+ ws = [(w[:-1], int(w[-1])) for w in s.split()]
+ ws.sort(key=lambda x: x[1])
+ return ' '.join(w for w, _ in ws)
+```
+
+```python
+class Solution:
+ def sortSentence(self, s: str) -> str:
+ ws = s.split()
+ ans = [None] * len(ws)
+ for w in ws:
+ ans[int(w[-1]) - 1] = w[:-1]
return ' '.join(ans)
```
@@ -64,11 +81,12 @@ class Solution:
```java
class Solution {
public String sortSentence(String s) {
- String[] words = s.split(" ");
- String[] ans = new String[words.length];
- for (String w : words) {
- int i = w.charAt(w.length() - 1) - '1';
- ans[i] = w.substring(0, w.length() - 1);
+ String[] ws = s.split(" ");
+ int n = ws.length;
+ String[] ans = new String[n];
+ for (int i = 0; i < n; ++i) {
+ String w = ws[i];
+ ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1);
}
return String.join(" ", ans);
}
@@ -81,17 +99,18 @@ class Solution {
class Solution {
public:
string sortSentence(string s) {
- istringstream is(s);
- string t;
- vector words;
- while (is >> t) words.push_back(t);
- vector res(words.size());
- for (auto& w : words) {
- int i = w[w.size() - 1] - '1';
- res[i] = w.substr(0, w.size() - 1);
+ istringstream iss(s);
+ string w;
+ vector ws;
+ while (iss >> w) {
+ ws.push_back(w);
+ }
+ vector ss(ws.size());
+ for (auto& w : ws) {
+ ss[w.back() - '1'] = w.substr(0, w.size() - 1);
}
string ans;
- for (auto& w : res) {
+ for (auto& w : ss) {
ans += w + " ";
}
ans.pop_back();
@@ -104,11 +123,10 @@ public:
```go
func sortSentence(s string) string {
- words := strings.Split(s, " ")
- ans := make([]string, len(words))
- for _, w := range words {
- i := w[len(w)-1] - '1'
- ans[i] = w[:len(w)-1]
+ ws := strings.Split(s, " ")
+ ans := make([]string, len(ws))
+ for _, w := range ws {
+ ans[w[len(w)-1]-'1'] = w[:len(w)-1]
}
return strings.Join(ans, " ")
}
@@ -122,11 +140,10 @@ func sortSentence(s string) string {
* @return {string}
*/
var sortSentence = function (s) {
- const words = s.split(' ');
- const ans = new Array(words.length);
- for (const w of words) {
- const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0);
- ans[i] = w.slice(0, w.length - 1);
+ const ws = s.split(' ');
+ const ans = Array(ws.length);
+ for (const w of ws) {
+ ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1);
}
return ans.join(' ');
};
@@ -136,11 +153,10 @@ var sortSentence = function (s) {
```ts
function sortSentence(s: string): string {
- const words = s.split(' ');
- const ans = new Array(words.length);
- for (const w of words) {
- const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0);
- ans[i] = w.slice(0, w.length - 1);
+ const ws = s.split(' ');
+ const ans = Array(ws.length);
+ for (const w of ws) {
+ ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1);
}
return ans.join(' ');
}
diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp b/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp
index 1f13c6dde845e..01a8e1017d68e 100644
--- a/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp
+++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp
@@ -1,20 +1,21 @@
-class Solution {
-public:
- string sortSentence(string s) {
- istringstream is(s);
- string t;
- vector words;
- while (is >> t) words.push_back(t);
- vector res(words.size());
- for (auto& w : words) {
- int i = w[w.size() - 1] - '1';
- res[i] = w.substr(0, w.size() - 1);
- }
- string ans;
- for (auto& w : res) {
- ans += w + " ";
- }
- ans.pop_back();
- return ans;
- }
+class Solution {
+public:
+ string sortSentence(string s) {
+ istringstream iss(s);
+ string w;
+ vector ws;
+ while (iss >> w) {
+ ws.push_back(w);
+ }
+ vector ss(ws.size());
+ for (auto& w : ws) {
+ ss[w.back() - '1'] = w.substr(0, w.size() - 1);
+ }
+ string ans;
+ for (auto& w : ss) {
+ ans += w + " ";
+ }
+ ans.pop_back();
+ return ans;
+ }
};
\ No newline at end of file
diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.go b/solution/1800-1899/1859.Sorting the Sentence/Solution.go
index 20517960bd125..e0d069b026b2d 100644
--- a/solution/1800-1899/1859.Sorting the Sentence/Solution.go
+++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.go
@@ -1,9 +1,8 @@
func sortSentence(s string) string {
- words := strings.Split(s, " ")
- ans := make([]string, len(words))
- for _, w := range words {
- i := w[len(w)-1] - '1'
- ans[i] = w[:len(w)-1]
+ ws := strings.Split(s, " ")
+ ans := make([]string, len(ws))
+ for _, w := range ws {
+ ans[w[len(w)-1]-'1'] = w[:len(w)-1]
}
return strings.Join(ans, " ")
}
\ No newline at end of file
diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.java b/solution/1800-1899/1859.Sorting the Sentence/Solution.java
index 6389492d7032b..cea8b91864566 100644
--- a/solution/1800-1899/1859.Sorting the Sentence/Solution.java
+++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.java
@@ -1,11 +1,12 @@
-class Solution {
- public String sortSentence(String s) {
- String[] words = s.split(" ");
- String[] ans = new String[words.length];
- for (String w : words) {
- int i = w.charAt(w.length() - 1) - '1';
- ans[i] = w.substring(0, w.length() - 1);
- }
- return String.join(" ", ans);
- }
+class Solution {
+ public String sortSentence(String s) {
+ String[] ws = s.split(" ");
+ int n = ws.length;
+ String[] ans = new String[n];
+ for (int i = 0; i < n; ++i) {
+ String w = ws[i];
+ ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1);
+ }
+ return String.join(" ", ans);
+ }
}
\ No newline at end of file
diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.js b/solution/1800-1899/1859.Sorting the Sentence/Solution.js
index 10608d1f73cd6..f1ad9eb287de3 100644
--- a/solution/1800-1899/1859.Sorting the Sentence/Solution.js
+++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.js
@@ -3,11 +3,10 @@
* @return {string}
*/
var sortSentence = function (s) {
- const words = s.split(' ');
- const ans = new Array(words.length);
- for (const w of words) {
- const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0);
- ans[i] = w.slice(0, w.length - 1);
+ const ws = s.split(' ');
+ const ans = Array(ws.length);
+ for (const w of ws) {
+ ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1);
}
return ans.join(' ');
};
diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.py b/solution/1800-1899/1859.Sorting the Sentence/Solution.py
index 3e9cfbfe3a495..bac4af524fec8 100644
--- a/solution/1800-1899/1859.Sorting the Sentence/Solution.py
+++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.py
@@ -1,8 +1,7 @@
-class Solution:
- def sortSentence(self, s: str) -> str:
- words = s.split()
- ans = [None] * len(words)
- for w in words:
- i = int(w[-1]) - 1
- ans[i] = w[:-1]
- return ' '.join(ans)
+class Solution:
+ def sortSentence(self, s: str) -> str:
+ ws = s.split()
+ ans = [None] * len(ws)
+ for w in ws:
+ ans[int(w[-1]) - 1] = w[:-1]
+ return " ".join(ans)
diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.ts b/solution/1800-1899/1859.Sorting the Sentence/Solution.ts
index 8baf02269b8ef..8c691873a4a97 100644
--- a/solution/1800-1899/1859.Sorting the Sentence/Solution.ts
+++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.ts
@@ -1,9 +1,8 @@
function sortSentence(s: string): string {
- const words = s.split(' ');
- const ans = new Array(words.length);
- for (const w of words) {
- const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0);
- ans[i] = w.slice(0, w.length - 1);
+ const ws = s.split(' ');
+ const ans = Array(ws.length);
+ for (const w of ws) {
+ ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1);
}
return ans.join(' ');
}
diff --git a/solution/1800-1899/1860.Incremental Memory Leak/README.md b/solution/1800-1899/1860.Incremental Memory Leak/README.md
index a52b5a27554ba..1fd6ff6c99677 100644
--- a/solution/1800-1899/1860.Incremental Memory Leak/README.md
+++ b/solution/1800-1899/1860.Incremental Memory Leak/README.md
@@ -51,7 +51,7 @@
**方法一:模拟**
-直接模拟内存的分配。
+我们直接模拟内存的分配。
假设 $t$ 为意外退出的时刻,那么两个内存条一定可以容纳 $t-1$ 时刻及以前消耗的内存,因此有:
@@ -59,7 +59,7 @@ $$
\sum_{i=1}^{t-1} i = \frac{t\times (t-1)}{2} \leq (m_1+m_2)
$$
-时间复杂度 $O(\sqrt{m1+m2})$,其中 $m_1$, $m_2$ 分别为两个内存条的内存大小。
+时间复杂度 $O(\sqrt{m_1+m_2})$,其中 $m_1$, $m_2$ 分别为两个内存条的内存大小。
diff --git a/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md b/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md
index 10fe24c658f3c..169841f2bb8ad 100644
--- a/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md
+++ b/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md
@@ -45,6 +45,18 @@
## Solutions
+**Solution 1: Simulation**
+
+We directly simulate the allocation of memory.
+
+Assume $t$ is the moment of unexpected exit, then the two memory sticks can definitely accommodate the memory consumed at the moment $t-1$ and before, so we have:
+
+$$
+\sum_{i=1}^{t-1} i = \frac{t\times (t-1)}{2} \leq (m_1+m_2)
+$$
+
+The time complexity is $O(\sqrt{m_1+m_2})$, where $m_1$ and $m_2$ are the sizes of the two memory sticks respectively.
+
### **Python3**
diff --git a/solution/1800-1899/1861.Rotating the Box/README_EN.md b/solution/1800-1899/1861.Rotating the Box/README_EN.md
index 3a9e765927fa7..beb5e46d8c82a 100644
--- a/solution/1800-1899/1861.Rotating the Box/README_EN.md
+++ b/solution/1800-1899/1861.Rotating the Box/README_EN.md
@@ -71,6 +71,12 @@
## Solutions
+**Solution 1: Queue Simulation**
+
+First, we rotate the matrix 90 degrees clockwise, then simulate the falling process of the stones in each column.
+
+The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively.
+
### **Python3**
diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md
index ec94b7dcc59d6..705002837f323 100644
--- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md
+++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md
@@ -68,6 +68,27 @@
+**方法一:二进制枚举**
+
+我们可以用二进制枚举的方法,枚举出所有的子集,然后计算每个子集的异或总和。
+
+具体地,我们在 $[0, 2^n)$ 的范围内枚举 $i$,其中 $n$ 是数组 $nums$ 的长度。如果 $i$ 的二进制表示的第 $j$ 位为 $1$,那么代表着 $nums$ 的第 $j$ 个元素在当前枚举的子集中;如果第 $j$ 位为 $0$,那么代表着 $nums$ 的第 $j$ 个元素不在当前枚举的子集中。我们可以根据 $i$ 的二进制表示,得到当前子集对应的异或总和,将其加到答案中即可。
+
+时间复杂度 $O(n \times 2^n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。
+
+**方法二:DFS**
+
+我们也可以使用深度优先搜索的方法,枚举出所有的子集,然后计算每个子集的异或总和。
+
+我们设计一个函数 $dfs(i, s)$,其中 $i$ 表示当前搜索到数组 $nums$ 的第 $i$ 个元素,$s$ 表示当前子集的异或总和。初始时,$i=0$, $s=0$。在搜索的过程中,每次我们都有两种选择:
+
+- 将 $nums$ 的第 $i$ 个元素加入当前子集,即 $dfs(i+1, s \oplus nums[i])$;
+- 将 $nums$ 的第 $i$ 个元素不加入当前子集,即 $dfs(i+1, s)$。
+
+当我们搜索完数组 $nums$ 的所有元素时,即 $i=n$ 时,当前子集的异或总和为 $s$,将其加到答案中即可。
+
+时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。
+
### **Python3**
@@ -77,17 +98,30 @@
```python
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
- def dfs(nums, depth, prev):
- self.res += prev
- for num in nums[depth:]:
- prev ^= num
- depth += 1
- dfs(nums, depth, prev)
- prev ^= num
-
- self.res = 0
- dfs(nums, 0, 0)
- return self.res
+ ans, n = 0, len(nums)
+ for i in range(1 << n):
+ s = 0
+ for j in range(n):
+ if i >> j & 1:
+ s ^= nums[j]
+ ans += s
+ return ans
+```
+
+```python
+class Solution:
+ def subsetXORSum(self, nums: List[int]) -> int:
+ def dfs(i: int, s: int):
+ nonlocal ans
+ if i >= len(nums):
+ ans += s
+ return
+ dfs(i + 1, s)
+ dfs(i + 1, s ^ nums[i])
+
+ ans = 0
+ dfs(0, 0)
+ return ans
```
### **Java**
@@ -96,24 +130,158 @@ class Solution:
```java
class Solution {
- private int res;
+ public int subsetXORSum(int[] nums) {
+ int n = nums.length;
+ int ans = 0;
+ for (int i = 0; i < 1 << n; ++i) {
+ int s = 0;
+ for (int j = 0; j < n; ++j) {
+ if ((i >> j & 1) == 1) {
+ s ^= nums[j];
+ }
+ }
+ ans += s;
+ }
+ return ans;
+ }
+}
+```
+
+```java
+class Solution {
+ private int ans;
+ private int[] nums;
public int subsetXORSum(int[] nums) {
- dfs(nums, 0, 0);
- return res;
+ this.nums = nums;
+ dfs(0, 0);
+ return ans;
}
- private void dfs(int[] nums, int depth, int prev) {
- res += prev;
- for (int i = depth; i < nums.length; ++i) {
- prev ^= nums[i];
- dfs(nums, ++depth, prev);
- prev ^= nums[i];
+ private void dfs(int i, int s) {
+ if (i >= nums.length) {
+ ans += s;
+ return;
}
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
}
}
```
+### **C++**
+
+```cpp
+class Solution {
+public:
+ int subsetXORSum(vector& nums) {
+ int n = nums.size();
+ int ans = 0;
+ for (int i = 0; i < 1 << n; ++i) {
+ int s = 0;
+ for (int j = 0; j < n; ++j) {
+ if (i >> j & 1) {
+ s ^= nums[j];
+ }
+ }
+ ans += s;
+ }
+ return ans;
+ }
+};
+```
+
+```cpp
+class Solution {
+public:
+ int subsetXORSum(vector& nums) {
+ int n = nums.size();
+ int ans = 0;
+ function dfs = [&](int i, int s) {
+ if (i >= n) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ };
+ dfs(0, 0);
+ return ans;
+ }
+};
+```
+
+### **Go**
+
+```go
+func subsetXORSum(nums []int) (ans int) {
+ n := len(nums)
+ for i := 0; i < 1<>j&1 == 1 {
+ s ^= x
+ }
+ }
+ ans += s
+ }
+ return
+}
+```
+
+```go
+func subsetXORSum(nums []int) (ans int) {
+ n := len(nums)
+ var dfs func(int, int)
+ dfs = func(i, s int) {
+ if i >= n {
+ ans += s
+ return
+ }
+ dfs(i+1, s)
+ dfs(i+1, s^nums[i])
+ }
+ dfs(0, 0)
+ return
+}
+```
+
+### **TypeScript**
+
+```ts
+function subsetXORSum(nums: number[]): number {
+ let ans = 0;
+ const n = nums.length;
+ for (let i = 0; i < 1 << n; ++i) {
+ let s = 0;
+ for (let j = 0; j < n; ++j) {
+ if ((i >> j) & 1) {
+ s ^= nums[j];
+ }
+ }
+ ans += s;
+ }
+ return ans;
+}
+```
+
+```ts
+function subsetXORSum(nums: number[]): number {
+ let ans = 0;
+ const n = nums.length;
+ const dfs = (i: number, s: number) => {
+ if (i >= n) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ };
+ dfs(0, 0);
+ return ans;
+}
+```
+
### **JavaScript**
```js
@@ -122,22 +290,40 @@ class Solution {
* @return {number}
*/
var subsetXORSum = function (nums) {
- let res = [];
- let prev = 0;
- dfs(nums, 0, prev, res);
- return res.reduce((a, c) => a + c, 0);
+ let ans = 0;
+ const n = nums.length;
+ for (let i = 0; i < 1 << n; ++i) {
+ let s = 0;
+ for (let j = 0; j < n; ++j) {
+ if ((i >> j) & 1) {
+ s ^= nums[j];
+ }
+ }
+ ans += s;
+ }
+ return ans;
};
+```
-function dfs(nums, depth, prev, res) {
- res.push(prev);
- for (let i = depth; i < nums.length; i++) {
- prev ^= nums[i];
- depth++;
- dfs(nums, depth, prev, res);
- // bracktrack
- prev ^= nums[i];
- }
-}
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var subsetXORSum = function (nums) {
+ let ans = 0;
+ const n = nums.length;
+ const dfs = (i, s) => {
+ if (i >= n) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ };
+ dfs(0, 0);
+ return ans;
+};
```
### **...**
diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md
index 0ddce174f9165..7c9c5b68cea25 100644
--- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md
+++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md
@@ -65,6 +65,27 @@
## Solutions
+**Solution 1: Binary Enumeration**
+
+We can use binary enumeration to enumerate all subsets, and then calculate the XOR sum of each subset.
+
+Specifically, we enumerate $i$ in the range $[0, 2^n)$, where $n$ is the length of the array $nums$. If the $j$th bit of the binary representation of $i$ is $1$, it means that the $j$th element of $nums$ is in the current subset; if the $j$th bit is $0$, it means that the $j$th element of $nums$ is not in the current subset. We can get the XOR sum of the current subset according to the binary representation of $i$, and add it to the answer.
+
+The time complexity is $O(n \times 2^n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.
+
+**Solution 2: DFS (Depth-First Search)**
+
+We can also use depth-first search to enumerate all subsets, and then calculate the XOR sum of each subset.
+
+We design a function $dfs(i, s)$, where $i$ represents the current search to the $i$th element of the array $nums$, and $s$ represents the XOR sum of the current subset. Initially, $i=0$, $s=0$. During the search, we have two choices each time:
+
+- Add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s \oplus nums[i])$;
+- Do not add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s)$.
+
+When we have searched all elements of the array $nums$, i.e., $i=n$, the XOR sum of the current subset is $s$, and we can add it to the answer.
+
+The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$.
+
### **Python3**
@@ -72,38 +93,185 @@
```python
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
- def dfs(nums, depth, prev):
- self.res += prev
- for num in nums[depth:]:
- prev ^= num
- depth += 1
- dfs(nums, depth, prev)
- prev ^= num
-
- self.res = 0
- dfs(nums, 0, 0)
- return self.res
+ ans, n = 0, len(nums)
+ for i in range(1 << n):
+ s = 0
+ for j in range(n):
+ if i >> j & 1:
+ s ^= nums[j]
+ ans += s
+ return ans
+```
+
+```python
+class Solution:
+ def subsetXORSum(self, nums: List[int]) -> int:
+ def dfs(i: int, s: int):
+ nonlocal ans
+ if i >= len(nums):
+ ans += s
+ return
+ dfs(i + 1, s)
+ dfs(i + 1, s ^ nums[i])
+
+ ans = 0
+ dfs(0, 0)
+ return ans
```
### **Java**
```java
class Solution {
- private int res;
+ public int subsetXORSum(int[] nums) {
+ int n = nums.length;
+ int ans = 0;
+ for (int i = 0; i < 1 << n; ++i) {
+ int s = 0;
+ for (int j = 0; j < n; ++j) {
+ if ((i >> j & 1) == 1) {
+ s ^= nums[j];
+ }
+ }
+ ans += s;
+ }
+ return ans;
+ }
+}
+```
+
+```java
+class Solution {
+ private int ans;
+ private int[] nums;
public int subsetXORSum(int[] nums) {
- dfs(nums, 0, 0);
- return res;
+ this.nums = nums;
+ dfs(0, 0);
+ return ans;
+ }
+
+ private void dfs(int i, int s) {
+ if (i >= nums.length) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ }
+}
+```
+
+### **C++**
+
+```cpp
+class Solution {
+public:
+ int subsetXORSum(vector& nums) {
+ int n = nums.size();
+ int ans = 0;
+ for (int i = 0; i < 1 << n; ++i) {
+ int s = 0;
+ for (int j = 0; j < n; ++j) {
+ if (i >> j & 1) {
+ s ^= nums[j];
+ }
+ }
+ ans += s;
+ }
+ return ans;
}
+};
+```
+
+```cpp
+class Solution {
+public:
+ int subsetXORSum(vector& nums) {
+ int n = nums.size();
+ int ans = 0;
+ function dfs = [&](int i, int s) {
+ if (i >= n) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ };
+ dfs(0, 0);
+ return ans;
+ }
+};
+```
+
+### **Go**
- private void dfs(int[] nums, int depth, int prev) {
- res += prev;
- for (int i = depth; i < nums.length; ++i) {
- prev ^= nums[i];
- dfs(nums, ++depth, prev);
- prev ^= nums[i];
+```go
+func subsetXORSum(nums []int) (ans int) {
+ n := len(nums)
+ for i := 0; i < 1<>j&1 == 1 {
+ s ^= x
+ }
+ }
+ ans += s
+ }
+ return
+}
+```
+
+```go
+func subsetXORSum(nums []int) (ans int) {
+ n := len(nums)
+ var dfs func(int, int)
+ dfs = func(i, s int) {
+ if i >= n {
+ ans += s
+ return
+ }
+ dfs(i+1, s)
+ dfs(i+1, s^nums[i])
+ }
+ dfs(0, 0)
+ return
+}
+```
+
+### **TypeScript**
+
+```ts
+function subsetXORSum(nums: number[]): number {
+ let ans = 0;
+ const n = nums.length;
+ for (let i = 0; i < 1 << n; ++i) {
+ let s = 0;
+ for (let j = 0; j < n; ++j) {
+ if ((i >> j) & 1) {
+ s ^= nums[j];
+ }
}
+ ans += s;
}
+ return ans;
+}
+```
+
+```ts
+function subsetXORSum(nums: number[]): number {
+ let ans = 0;
+ const n = nums.length;
+ const dfs = (i: number, s: number) => {
+ if (i >= n) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ };
+ dfs(0, 0);
+ return ans;
}
```
@@ -115,22 +283,40 @@ class Solution {
* @return {number}
*/
var subsetXORSum = function (nums) {
- let res = [];
- let prev = 0;
- dfs(nums, 0, prev, res);
- return res.reduce((a, c) => a + c, 0);
+ let ans = 0;
+ const n = nums.length;
+ for (let i = 0; i < 1 << n; ++i) {
+ let s = 0;
+ for (let j = 0; j < n; ++j) {
+ if ((i >> j) & 1) {
+ s ^= nums[j];
+ }
+ }
+ ans += s;
+ }
+ return ans;
};
+```
-function dfs(nums, depth, prev, res) {
- res.push(prev);
- for (let i = depth; i < nums.length; i++) {
- prev ^= nums[i];
- depth++;
- dfs(nums, depth, prev, res);
- // bracktrack
- prev ^= nums[i];
- }
-}
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var subsetXORSum = function (nums) {
+ let ans = 0;
+ const n = nums.length;
+ const dfs = (i, s) => {
+ if (i >= n) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ };
+ dfs(0, 0);
+ return ans;
+};
```
### **...**
diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp
new file mode 100644
index 0000000000000..96a107b07cad6
--- /dev/null
+++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp
@@ -0,0 +1,17 @@
+class Solution {
+public:
+ int subsetXORSum(vector& nums) {
+ int n = nums.size();
+ int ans = 0;
+ for (int i = 0; i < 1 << n; ++i) {
+ int s = 0;
+ for (int j = 0; j < n; ++j) {
+ if (i >> j & 1) {
+ s ^= nums[j];
+ }
+ }
+ ans += s;
+ }
+ return ans;
+ }
+};
\ No newline at end of file
diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go
new file mode 100644
index 0000000000000..84693f1999b84
--- /dev/null
+++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go
@@ -0,0 +1,14 @@
+func subsetXORSum(nums []int) (ans int) {
+ n := len(nums)
+ var dfs func(int, int)
+ dfs = func(i, s int) {
+ if i >= n {
+ ans += s
+ return
+ }
+ dfs(i+1, s)
+ dfs(i+1, s^nums[i])
+ }
+ dfs(0, 0)
+ return
+}
\ No newline at end of file
diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java
index 0de7bcd98218d..4bf80cd0de29a 100644
--- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java
+++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java
@@ -1,17 +1,19 @@
-class Solution {
- private int res;
-
- public int subsetXORSum(int[] nums) {
- dfs(nums, 0, 0);
- return res;
- }
-
- private void dfs(int[] nums, int depth, int prev) {
- res += prev;
- for (int i = depth; i < nums.length; ++i) {
- prev ^= nums[i];
- dfs(nums, ++depth, prev);
- prev ^= nums[i];
- }
- }
+class Solution {
+ private int ans;
+ private int[] nums;
+
+ public int subsetXORSum(int[] nums) {
+ this.nums = nums;
+ dfs(0, 0);
+ return ans;
+ }
+
+ private void dfs(int i, int s) {
+ if (i >= nums.length) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ }
}
\ No newline at end of file
diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js
index 37832de9befcd..ba314b524a976 100644
--- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js
+++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js
@@ -3,19 +3,16 @@
* @return {number}
*/
var subsetXORSum = function (nums) {
- let res = [];
- let prev = 0;
- dfs(nums, 0, prev, res);
- return res.reduce((a, c) => a + c, 0);
+ let ans = 0;
+ const n = nums.length;
+ const dfs = (i, s) => {
+ if (i >= n) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ };
+ dfs(0, 0);
+ return ans;
};
-
-function dfs(nums, depth, prev, res) {
- res.push(prev);
- for (let i = depth; i < nums.length; i++) {
- prev ^= nums[i];
- depth++;
- dfs(nums, depth, prev, res);
- // bracktrack
- prev ^= nums[i];
- }
-}
diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py
index a2f9a779f8341..2e180076e0817 100644
--- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py
+++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py
@@ -1,13 +1,13 @@
-class Solution:
- def subsetXORSum(self, nums: List[int]) -> int:
- def dfs(nums, depth, prev):
- self.res += prev
- for num in nums[depth:]:
- prev ^= num
- depth += 1
- dfs(nums, depth, prev)
- prev ^= num
-
- self.res = 0
- dfs(nums, 0, 0)
- return self.res
+class Solution:
+ def subsetXORSum(self, nums: List[int]) -> int:
+ def dfs(i: int, s: int):
+ nonlocal ans
+ if i >= len(nums):
+ ans += s
+ return
+ dfs(i + 1, s)
+ dfs(i + 1, s ^ nums[i])
+
+ ans = 0
+ dfs(0, 0)
+ return ans
diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts
new file mode 100644
index 0000000000000..8bd8da85b5597
--- /dev/null
+++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts
@@ -0,0 +1,14 @@
+function subsetXORSum(nums: number[]): number {
+ let ans = 0;
+ const n = nums.length;
+ const dfs = (i: number, s: number) => {
+ if (i >= n) {
+ ans += s;
+ return;
+ }
+ dfs(i + 1, s);
+ dfs(i + 1, s ^ nums[i]);
+ };
+ dfs(0, 0);
+ return ans;
+}