diff --git a/basic/sorting/BubbleSort/README.md b/basic/sorting/BubbleSort/README.md
index a8e97ac791e3c..499475c9d12e0 100644
--- a/basic/sorting/BubbleSort/README.md
+++ b/basic/sorting/BubbleSort/README.md
@@ -8,7 +8,34 @@
-### **Java**
+```python
+def bubbleSort(arr):
+ n = len(arr)
+ # Iterate over all array elements
+ for i in range(n):
+ # Last i elements are already in place
+ for j in range(n - i - 1):
+ if arr[j] > arr[j + 1]:
+ arr[j], arr[j + 1] = arr[j + 1], arr[j]
+
+
+# 改进版本
+def bubbleSort(arr):
+ n = len(arr)
+ for i in range(n - 1):
+ has_change = False
+ for j in range(n - i - 1):
+ if arr[j] > arr[j + 1]:
+ arr[j], arr[j + 1] = arr[j + 1], arr[j]
+ has_change = True
+ if not has_change:
+ break
+
+
+arr = [64, 34, 25, 12, 22, 11, 90]
+bubbleSort(arr)
+print(arr)
+```
```java
import java.util.Arrays;
@@ -42,35 +69,34 @@ public class BubbleSort {
}
```
-### **JavaScript**
+```cpp
+#include
+#include
-```js
-function bubbleSort(inputArr) {
- for (let i = inputArr.length - 1; i > 0; i--) {
- let hasChange = false;
- for (let j = 0; j < i; j++) {
- if (inputArr[j] > inputArr[j + 1]) {
- const temp = inputArr[j];
- inputArr[j] = inputArr[j + 1];
- inputArr[j + 1] = temp;
- hasChange = true;
- }
- }
+using namespace std;
- if (!hasChange) {
- break;
+void bubbleSort(vector& arr) {
+ int n = arr.size();
+ for (int i = 0; i < n - 1; ++i) {
+ bool change = false;
+ for (int j = 0; j < n - i - 1; ++j) {
+ if (arr[j] > arr[j + 1]) {
+ swap(arr[j], arr[j + 1]);
+ change = true;
+ }
}
+ if (!change) break;
}
-
- return inputArr;
}
-const arr = [6, 3, 2, 1, 5];
-console.log(bubbleSort(arr));
+int main() {
+ vector arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
+ bubbleSort(arr);
+ for (int v : arr) cout << v << " ";
+ cout << endl;
+}
```
-### **Go**
-
```go
package main
@@ -96,38 +122,6 @@ func main() {
}
```
-### **C++**
-
-```cpp
-#include
-#include
-
-using namespace std;
-
-void bubbleSort(vector& arr) {
- int n = arr.size();
- for (int i = 0; i < n - 1; ++i) {
- bool change = false;
- for (int j = 0; j < n - i - 1; ++j) {
- if (arr[j] > arr[j + 1]) {
- swap(arr[j], arr[j + 1]);
- change = true;
- }
- }
- if (!change) break;
- }
-}
-
-int main() {
- vector arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
- bubbleSort(arr);
- for (int v : arr) cout << v << " ";
- cout << endl;
-}
-```
-
-### **Rust**
-
```rust
fn bubble_sort(nums: &mut Vec) {
let n = nums.len();
@@ -149,7 +143,30 @@ fn main() {
}
```
-### **C#**
+```js
+function bubbleSort(inputArr) {
+ for (let i = inputArr.length - 1; i > 0; i--) {
+ let hasChange = false;
+ for (let j = 0; j < i; j++) {
+ if (inputArr[j] > inputArr[j + 1]) {
+ const temp = inputArr[j];
+ inputArr[j] = inputArr[j + 1];
+ inputArr[j + 1] = temp;
+ hasChange = true;
+ }
+ }
+
+ if (!hasChange) {
+ break;
+ }
+ }
+
+ return inputArr;
+}
+
+const arr = [6, 3, 2, 1, 5];
+console.log(bubbleSort(arr));
+```
```cs
using static System.Console;
@@ -199,49 +216,6 @@ public class Program
}
```
-### **Python3**
-
-```python
-def bubbleSort(arr):
- n = len(arr)
- # Iterate over all array elements
- for i in range(n):
- # Last i elements are already in place
- for j in range(n - i - 1):
- if arr[j] > arr[j + 1]:
- arr[j], arr[j + 1] = arr[j + 1], arr[j]
-
-
-# 改进版本
-def bubbleSort(arr):
- n = len(arr)
- for i in range(n - 1):
- has_change = False
- for j in range(n - i - 1):
- if arr[j] > arr[j + 1]:
- arr[j], arr[j + 1] = arr[j + 1], arr[j]
- has_change = True
- if not has_change:
- break
-
-
-arr = [64, 34, 25, 12, 22, 11, 90]
-bubbleSort(arr)
-print(arr)
-```
-
-## 算法分析
-
-空间复杂度 $O(1)$、时间复杂度 $O(n^2)$。
-
-分情况讨论:
-
-1. 给定的数组按照顺序已经排好:只需要进行 $n-1$ 次比较,两两交换次数为 0,时间复杂度为 $O(n)$,这是最好的情况。
-2. 给定的数组按照逆序排列:需要进行 $\frac{n\times (n-1)}{2}$ 次比较,时间复杂度为 $O(n^2)$,这是最坏的情况。
-3. 给定的数组杂乱无章。在这种情况下,平均时间复杂度 $O(n^2)$。
-
-因此,时间复杂度是 $O(n^2)$,这是一种稳定的排序算法。
-
-> 稳定是指,两个相等的数,在排序过后,相对位置保持不变。
+
diff --git a/basic/sorting/HeapSort/README.md b/basic/sorting/HeapSort/README.md
index ba368648050ba..5a0d825404206 100644
--- a/basic/sorting/HeapSort/README.md
+++ b/basic/sorting/HeapSort/README.md
@@ -286,4 +286,219 @@ func main() {
}
```
+## 解法
+
+### 方法一
+
+
+
+```python
+n, m = list(map(int, input().split(" ")))
+h = [0] + list(map(int, input().split(" ")))
+
+size = n
+
+
+def down(u):
+ t = u
+ if u * 2 <= size and h[u * 2] < h[t]:
+ t = u * 2
+ if u * 2 + 1 <= size and h[u * 2 + 1] < h[t]:
+ t = u * 2 + 1
+ if t != u:
+ h[t], h[u] = h[u], h[t]
+ down(t)
+
+
+def up(u):
+ while u // 2 > 0 and h[u // 2] > h[u]:
+ h[u // 2], h[u] = h[u], h[u // 2]
+ u //= 2
+
+
+for i in range(n // 2, 0, -1):
+ down(i)
+
+res = []
+for i in range(m):
+ res.append(h[1])
+ h[1] = h[size]
+ size -= 1
+ down(1)
+
+print(' '.join(list(map(str, res))))
+```
+
+```java
+import java.util.Scanner;
+
+public class Main {
+ private static int[] h = new int[100010];
+ private static int size;
+
+ public static void main(String[] args) {
+ Scanner sc = new Scanner(System.in);
+ int n = sc.nextInt(), m = sc.nextInt();
+ for (int i = 1; i <= n; ++i) {
+ h[i] = sc.nextInt();
+ }
+ size = n;
+ for (int i = n / 2; i > 0; --i) {
+ down(i);
+ }
+ while (m-- > 0) {
+ System.out.print(h[1] + " ");
+ h[1] = h[size--];
+ down(1);
+ }
+ }
+
+ public static void down(int u) {
+ int t = u;
+ if (u * 2 <= size && h[u * 2] < h[t]) {
+ t = u * 2;
+ }
+ if (u * 2 + 1 <= size && h[u * 2 + 1] < h[t]) {
+ t = u * 2 + 1;
+ }
+ if (t != u) {
+ swap(t, u);
+ down(t);
+ }
+ }
+
+ public static void up(int u) {
+ while (u / 2 > 0 && h[u / 2] > h[u]) {
+ swap(u / 2, u);
+ u /= 2;
+ }
+ }
+
+ public static void swap(int i, int j) {
+ int t = h[i];
+ h[i] = h[j];
+ h[j] = t;
+ }
+}
+```
+
+```go
+package main
+
+import "fmt"
+
+const N = 100010
+
+var (
+ size int
+ h []int
+)
+
+func up(u int) {
+ for u/2 != 0 && h[u/2] > h[u] { //父节点比当前结点小
+ h[u/2], h[u] = h[u], h[u/2] //交换
+ u /= 2
+ }
+}
+func down(u int) {
+ t := u //t 最小值
+ if u*2 <= size && h[2*u] < h[t] { //左孩子存在且小于t
+ t = u * 2
+ }
+ if u*2+1 <= size && h[2*u+1] < h[t] { //右孩子存在且小于t
+ t = 2*u + 1
+ }
+ if u != t {
+ h[u], h[t] = h[t], h[u]
+ down(t) //递归处理
+ }
+}
+func main() {
+ var n, m int
+ h = make([]int, N)
+ fmt.Scanf("%d%d", &n, &m)
+ //创建一维数组1
+ for i := 1; i <= n; i++ {
+ fmt.Scanf("%d", &h[i])
+ }
+ size = n
+ // 一维数组变为小根堆
+ for i := n / 2; i != 0; i-- {
+ down(i)
+ }
+
+ for ; m != 0; m-- {
+ fmt.Printf("%d ", h[1])
+ h[1] = h[size]
+ size--
+ down(1)
+ }
+}
+```
+
+```rust
+use std::io;
+
+fn heap_sort(nums: &mut Vec) {
+ let n = nums.len();
+ for i in (0..n / 2).rev() {
+ sink(nums, i, n);
+ }
+ for i in (1..n).rev() {
+ let temp = nums[0];
+ nums[0] = nums[i];
+ nums[i] = temp;
+ sink(nums, 0, i);
+ }
+}
+
+fn sink(nums: &mut Vec, mut i: usize, n: usize) {
+ loop {
+ let left = i * 2 + 1;
+ let right = left + 1;
+ let mut largest = i;
+ if left < n && nums[left] > nums[largest] {
+ largest = left;
+ }
+ if right < n && nums[right] > nums[largest] {
+ largest = right;
+ }
+ if largest == i {
+ break;
+ }
+ let temp = nums[i];
+ nums[i] = nums[largest];
+ nums[largest] = temp;
+ i = largest;
+ }
+}
+
+fn main() -> io::Result<()> {
+ let mut s = String::new();
+ io::stdin().read_line(&mut s)?;
+ let s: Vec = s
+ .split(' ')
+ .map(|s| s.trim().parse().unwrap())
+ .collect();
+ // let n = s[0];
+ let m = s[1];
+
+ let mut nums = String::new();
+ io::stdin().read_line(&mut nums)?;
+ let mut nums: Vec = nums
+ .split(' ')
+ .map(|s| s.trim().parse().unwrap())
+ .collect();
+
+ heap_sort(&mut nums);
+ for num in nums.iter().take(m) {
+ print!("{} ", num);
+ }
+
+ Ok(())
+}
+```
+
+
+
diff --git a/basic/sorting/InsertionSort/README.md b/basic/sorting/InsertionSort/README.md
index 6f0ead5860e15..a6a2c8094fc9b 100644
--- a/basic/sorting/InsertionSort/README.md
+++ b/basic/sorting/InsertionSort/README.md
@@ -17,7 +17,22 @@
-### **Java**
+```python
+def insertion_sort(array):
+ for i in range(len(array)):
+ cur_index = i
+ while array[cur_index - 1] > array[cur_index] and cur_index - 1 >= 0:
+ array[cur_index], array[cur_index - 1] = (
+ array[cur_index - 1],
+ array[cur_index],
+ )
+ cur_index -= 1
+ return array
+
+
+array = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21]
+print(insertion_sort(array))
+```
```java
import java.util.Arrays;
@@ -42,53 +57,6 @@ public class InsertionSort {
}
```
-### **JavaScript**
-
-```js
-function insertionSort(inputArr) {
- let len = inputArr.length;
- for (let i = 1; i <= len - 1; i++) {
- let temp = inputArr[i];
- let j = i - 1;
- while (j >= 0 && inputArr[j] > temp) {
- inputArr[j + 1] = inputArr[j];
- j--;
- }
- inputArr[j + 1] = temp;
- }
- return inputArr;
-}
-
-let arr = [6, 3, 2, 1, 5];
-console.log(insertionSort(arr));
-```
-
-### **Go**
-
-```go
-package main
-
-import "fmt"
-
-func insertionSort(nums []int) {
- for i, n := 1, len(nums); i < n; i++ {
- j, num := i-1, nums[i]
- for ; j >= 0 && nums[j] > num; j-- {
- nums[j+1] = nums[j]
- }
- nums[j+1] = num
- }
-}
-
-func main() {
- nums := []int{1, 2, 7, 9, 5, 8}
- insertionSort(nums)
- fmt.Println(nums)
-}
-```
-
-### **C++**
-
```cpp
#include
#include
@@ -128,7 +96,27 @@ int main() {
}
```
-### **Rust**
+```go
+package main
+
+import "fmt"
+
+func insertionSort(nums []int) {
+ for i, n := 1, len(nums); i < n; i++ {
+ j, num := i-1, nums[i]
+ for ; j >= 0 && nums[j] > num; j-- {
+ nums[j+1] = nums[j]
+ }
+ nums[j+1] = num
+ }
+}
+
+func main() {
+ nums := []int{1, 2, 7, 9, 5, 8}
+ insertionSort(nums)
+ fmt.Println(nums)
+}
+```
```rust
fn insertion_sort(nums: &mut Vec) {
@@ -151,7 +139,24 @@ fn main() {
}
```
-### **C#**
+```js
+function insertionSort(inputArr) {
+ let len = inputArr.length;
+ for (let i = 1; i <= len - 1; i++) {
+ let temp = inputArr[i];
+ let j = i - 1;
+ while (j >= 0 && inputArr[j] > temp) {
+ inputArr[j + 1] = inputArr[j];
+ j--;
+ }
+ inputArr[j + 1] = temp;
+ }
+ return inputArr;
+}
+
+let arr = [6, 3, 2, 1, 5];
+console.log(insertionSort(arr));
+```
```cs
using System.Diagnostics;
@@ -191,35 +196,6 @@ public class Program
}
```
-### **Python3**
-
-```python
-def insertion_sort(array):
- for i in range(len(array)):
- cur_index = i
- while array[cur_index - 1] > array[cur_index] and cur_index - 1 >= 0:
- array[cur_index], array[cur_index - 1] = (
- array[cur_index - 1],
- array[cur_index],
- )
- cur_index -= 1
- return array
-
-
-array = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21]
-print(insertion_sort(array))
-```
-
-## 算法分析
-
-空间复杂度 $O(1)$,时间复杂度 $O(n^2)$。
-
-分情况讨论:
-
-1. 给定的数组按照顺序排好序:只需要进行 $n-1$ 次比较,两两交换次数为 0,时间复杂度为 $O(n)$,这是最好的情况。
-1. 给定的数组按照逆序排列:需要进行 $\frac{n\times (n-1)}{2}$ 次比较,时间复杂度为 $O(n^2)$,这是最坏的情况。
-1. 给定的数组杂乱无章:在这种情况下,平均时间复杂度是 $O(n^2)$。
-
-因此,时间复杂度是 $O(n^2)$,这也是一种稳定的排序算法。
+
diff --git a/basic/sorting/MergeSort/README.md b/basic/sorting/MergeSort/README.md
index 160df0adee76d..1d6bf723ee893 100644
--- a/basic/sorting/MergeSort/README.md
+++ b/basic/sorting/MergeSort/README.md
@@ -73,8 +73,6 @@ void mergeSort(int[] nums, int left, int right) {
-### **Python3**
-
```python
N = int(input())
nums = list(map(int, input().split()))
@@ -112,8 +110,6 @@ merge_sort(nums, 0, N - 1)
print(' '.join(list(map(str, nums))))
```
-### **Java**
-
```java
import java.util.Scanner;
@@ -161,65 +157,43 @@ public class Main {
}
```
-### **JavaScript**
-
-```js
-var buf = '';
+```cpp
+#include
-process.stdin.on('readable', function () {
- var chunk = process.stdin.read();
- if (chunk) buf += chunk.toString();
-});
+using namespace std;
-let getInputArgs = line => {
- return line
- .split(' ')
- .filter(s => s !== '')
- .map(x => parseInt(x));
-};
+const int N = 1e6 + 10;
-function mergeSort(nums, left, right) {
- if (left >= right) {
- return;
- }
+int n;
+int nums[N];
+int tmp[N];
- const mid = (left + right) >> 1;
- mergeSort(nums, left, mid);
- mergeSort(nums, mid + 1, right);
- let i = left;
- let j = mid + 1;
- let tmp = [];
+void merge_sort(int nums[], int left, int right) {
+ if (left >= right) return;
+ int mid = (left + right) >> 1;
+ merge_sort(nums, left, mid);
+ merge_sort(nums, mid + 1, right);
+ int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
- if (nums[i] <= nums[j]) {
- tmp.push(nums[i++]);
- } else {
- tmp.push(nums[j++]);
- }
- }
- while (i <= mid) {
- tmp.push(nums[i++]);
- }
- while (j <= right) {
- tmp.push(nums[j++]);
- }
- for (i = left, j = 0; i <= right; ++i, ++j) {
- nums[i] = tmp[j];
+ if (nums[i] <= nums[j])
+ tmp[k++] = nums[i++];
+ else
+ tmp[k++] = nums[j++];
}
+ while (i <= mid) tmp[k++] = nums[i++];
+ while (j <= right) tmp[k++] = nums[j++];
+ for (i = left, j = 0; i <= right; ++i, ++j) nums[i] = tmp[j];
}
-process.stdin.on('end', function () {
- buf.split('\n').forEach(function (line, lineIdx) {
- if (lineIdx % 2 === 1) {
- nums = getInputArgs(line);
- mergeSort(nums, 0, nums.length - 1);
- console.log(nums.join(' '));
- }
- });
-});
+int main() {
+ int n;
+ scanf("%d", &n);
+ for (int i = 0; i < n; ++i) scanf("%d", &nums[i]);
+ merge_sort(nums, 0, n - 1);
+ for (int i = 0; i < n; ++i) printf("%d ", nums[i]);
+}
```
-### **Go**
-
```go
package main
@@ -272,47 +246,6 @@ func main() {
}
```
-### **C++**
-
-```cpp
-#include
-
-using namespace std;
-
-const int N = 1e6 + 10;
-
-int n;
-int nums[N];
-int tmp[N];
-
-void merge_sort(int nums[], int left, int right) {
- if (left >= right) return;
- int mid = (left + right) >> 1;
- merge_sort(nums, left, mid);
- merge_sort(nums, mid + 1, right);
- int i = left, j = mid + 1, k = 0;
- while (i <= mid && j <= right) {
- if (nums[i] <= nums[j])
- tmp[k++] = nums[i++];
- else
- tmp[k++] = nums[j++];
- }
- while (i <= mid) tmp[k++] = nums[i++];
- while (j <= right) tmp[k++] = nums[j++];
- for (i = left, j = 0; i <= right; ++i, ++j) nums[i] = tmp[j];
-}
-
-int main() {
- int n;
- scanf("%d", &n);
- for (int i = 0; i < n; ++i) scanf("%d", &nums[i]);
- merge_sort(nums, 0, n - 1);
- for (int i = 0; i < n; ++i) printf("%d ", nums[i]);
-}
-```
-
-### **Rust**
-
```rust
use std::io;
@@ -373,4 +306,61 @@ fn main() -> io::Result<()> {
}
```
+```js
+var buf = '';
+
+process.stdin.on('readable', function () {
+ var chunk = process.stdin.read();
+ if (chunk) buf += chunk.toString();
+});
+
+let getInputArgs = line => {
+ return line
+ .split(' ')
+ .filter(s => s !== '')
+ .map(x => parseInt(x));
+};
+
+function mergeSort(nums, left, right) {
+ if (left >= right) {
+ return;
+ }
+
+ const mid = (left + right) >> 1;
+ mergeSort(nums, left, mid);
+ mergeSort(nums, mid + 1, right);
+ let i = left;
+ let j = mid + 1;
+ let tmp = [];
+ while (i <= mid && j <= right) {
+ if (nums[i] <= nums[j]) {
+ tmp.push(nums[i++]);
+ } else {
+ tmp.push(nums[j++]);
+ }
+ }
+ while (i <= mid) {
+ tmp.push(nums[i++]);
+ }
+ while (j <= right) {
+ tmp.push(nums[j++]);
+ }
+ for (i = left, j = 0; i <= right; ++i, ++j) {
+ nums[i] = tmp[j];
+ }
+}
+
+process.stdin.on('end', function () {
+ buf.split('\n').forEach(function (line, lineIdx) {
+ if (lineIdx % 2 === 1) {
+ nums = getInputArgs(line);
+ mergeSort(nums, 0, nums.length - 1);
+ console.log(nums.join(' '));
+ }
+ });
+});
+```
+
+
+
diff --git a/basic/sorting/QuickSort/README.md b/basic/sorting/QuickSort/README.md
index bf09625d5e6b0..4cd6ce6a66da4 100644
--- a/basic/sorting/QuickSort/README.md
+++ b/basic/sorting/QuickSort/README.md
@@ -66,8 +66,6 @@ void quickSort(int[] nums, int left, int right) {
-### **Python3**
-
```python
N = int(input())
nums = list(map(int, input().split()))
@@ -97,8 +95,6 @@ quick_sort(nums, 0, N - 1)
print(' '.join(list(map(str, nums))))
```
-### **Java**
-
```java
import java.util.Scanner;
@@ -139,57 +135,40 @@ public class Main {
}
```
-### **JavaScript**
-
-```js
-var buf = '';
+```cpp
+#include
-process.stdin.on('readable', function () {
- var chunk = process.stdin.read();
- if (chunk) buf += chunk.toString();
-});
+using namespace std;
-let getInputArgs = line => {
- return line
- .split(' ')
- .filter(s => s !== '')
- .map(x => parseInt(x));
-};
+const int N = 1e6 + 10;
-function quickSort(nums, left, right) {
- if (left >= right) {
- return;
- }
+int n;
+int nums[N];
- let i = left - 1;
- let j = right + 1;
- let x = nums[(left + right) >> 1];
+void quick_sort(int nums[], int left, int right) {
+ if (left >= right) return;
+ int i = left - 1, j = right + 1;
+ int x = nums[left + right >> 1];
while (i < j) {
- while (nums[++i] < x);
- while (nums[--j] > x);
- if (i < j) {
- const t = nums[i];
- nums[i] = nums[j];
- nums[j] = t;
- }
+ while (nums[++i] < x)
+ ;
+ while (nums[--j] > x)
+ ;
+ if (i < j) swap(nums[i], nums[j]);
}
- quickSort(nums, left, j);
- quickSort(nums, j + 1, right);
+ quick_sort(nums, left, j);
+ quick_sort(nums, j + 1, right);
}
-process.stdin.on('end', function () {
- buf.split('\n').forEach(function (line, lineIdx) {
- if (lineIdx % 2 === 1) {
- nums = getInputArgs(line);
- quickSort(nums, 0, nums.length - 1);
- console.log(nums.join(' '));
- }
- });
-});
+int main() {
+ int n;
+ scanf("%d", &n);
+ for (int i = 0; i < n; ++i) scanf("%d", &nums[i]);
+ quick_sort(nums, 0, n - 1);
+ for (int i = 0; i < n; ++i) printf("%d ", nums[i]);
+}
```
-### **Go**
-
```go
package main
@@ -238,8 +217,6 @@ func main() {
}
```
-### **Rust**
-
```rust
use rand::Rng; // 0.7.2
use std::io;
@@ -294,40 +271,53 @@ fn main() -> io::Result<()> {
}
```
-### **C++**
-
-```cpp
-#include
+```js
+var buf = '';
-using namespace std;
+process.stdin.on('readable', function () {
+ var chunk = process.stdin.read();
+ if (chunk) buf += chunk.toString();
+});
-const int N = 1e6 + 10;
+let getInputArgs = line => {
+ return line
+ .split(' ')
+ .filter(s => s !== '')
+ .map(x => parseInt(x));
+};
-int n;
-int nums[N];
+function quickSort(nums, left, right) {
+ if (left >= right) {
+ return;
+ }
-void quick_sort(int nums[], int left, int right) {
- if (left >= right) return;
- int i = left - 1, j = right + 1;
- int x = nums[left + right >> 1];
+ let i = left - 1;
+ let j = right + 1;
+ let x = nums[(left + right) >> 1];
while (i < j) {
- while (nums[++i] < x)
- ;
- while (nums[--j] > x)
- ;
- if (i < j) swap(nums[i], nums[j]);
+ while (nums[++i] < x);
+ while (nums[--j] > x);
+ if (i < j) {
+ const t = nums[i];
+ nums[i] = nums[j];
+ nums[j] = t;
+ }
}
- quick_sort(nums, left, j);
- quick_sort(nums, j + 1, right);
+ quickSort(nums, left, j);
+ quickSort(nums, j + 1, right);
}
-int main() {
- int n;
- scanf("%d", &n);
- for (int i = 0; i < n; ++i) scanf("%d", &nums[i]);
- quick_sort(nums, 0, n - 1);
- for (int i = 0; i < n; ++i) printf("%d ", nums[i]);
-}
+process.stdin.on('end', function () {
+ buf.split('\n').forEach(function (line, lineIdx) {
+ if (lineIdx % 2 === 1) {
+ nums = getInputArgs(line);
+ quickSort(nums, 0, nums.length - 1);
+ console.log(nums.join(' '));
+ }
+ });
+});
```
+
+
diff --git a/basic/sorting/SelectionSort/README.md b/basic/sorting/SelectionSort/README.md
index 42601873043e0..74cea0ebb3f8c 100644
--- a/basic/sorting/SelectionSort/README.md
+++ b/basic/sorting/SelectionSort/README.md
@@ -6,7 +6,21 @@
-### **Java**
+```python
+def selection_sort(arr):
+ n = len(arr)
+ for i in range(n - 1):
+ min_index = i
+ for j in range(i + 1, n):
+ if arr[j] < arr[min_index]:
+ min_index = j
+ arr[min_index], arr[i] = arr[i], arr[min_index]
+
+
+arr = [26, 11, 99, 33, 69, 77, 55, 56, 67]
+selection_sort(arr)
+print(arr)
+```
```java
import java.util.Arrays;
@@ -39,57 +53,6 @@ public class SelectionSort {
}
```
-### **JavaScript**
-
-```js
-function selectionSort(inputArr) {
- let len = inputArr.length;
- for (let i = 0; i <= len - 2; i++) {
- let j = i;
- let min = j;
- while (j <= len - 1) {
- if (inputArr[j] < inputArr[min]) min = j;
- j++;
- }
- let temp = inputArr[i];
- inputArr[i] = inputArr[min];
- inputArr[min] = temp;
- }
- return inputArr;
-}
-
-let arr = [6, 3, 2, 1, 5];
-console.log(selectionSort(arr));
-```
-
-### **Go**
-
-```go
-package main
-
-import "fmt"
-
-func selectionSort(nums []int) {
- for i, n := 0, len(nums); i < n-1; i++ {
- minIndex := i
- for j := i + 1; j < n; j++ {
- if nums[j] < nums[minIndex] {
- minIndex = j
- }
- }
- nums[minIndex], nums[i] = nums[i], nums[minIndex]
- }
-}
-
-func main() {
- nums := []int{1, 2, 7, 9, 5, 8}
- selectionSort(nums)
- fmt.Println(nums)
-}
-```
-
-### **C++**
-
```cpp
#include
#include
@@ -128,7 +91,29 @@ int main(void) {
}
```
-### **Rust**
+```go
+package main
+
+import "fmt"
+
+func selectionSort(nums []int) {
+ for i, n := 0, len(nums); i < n-1; i++ {
+ minIndex := i
+ for j := i + 1; j < n; j++ {
+ if nums[j] < nums[minIndex] {
+ minIndex = j
+ }
+ }
+ nums[minIndex], nums[i] = nums[i], nums[minIndex]
+ }
+}
+
+func main() {
+ nums := []int{1, 2, 7, 9, 5, 8}
+ selectionSort(nums)
+ fmt.Println(nums)
+}
+```
```rust
fn selection_sort(nums: &mut Vec) {
@@ -153,7 +138,26 @@ fn main() {
}
```
-### **C#**
+```js
+function selectionSort(inputArr) {
+ let len = inputArr.length;
+ for (let i = 0; i <= len - 2; i++) {
+ let j = i;
+ let min = j;
+ while (j <= len - 1) {
+ if (inputArr[j] < inputArr[min]) min = j;
+ j++;
+ }
+ let temp = inputArr[i];
+ inputArr[i] = inputArr[min];
+ inputArr[min] = temp;
+ }
+ return inputArr;
+}
+
+let arr = [6, 3, 2, 1, 5];
+console.log(selectionSort(arr));
+```
```cs
using static System.Console;
@@ -192,35 +196,8 @@ public class Program
}
}
-
-```
-
-### **Python3**
-
-```python
-def selection_sort(arr):
- n = len(arr)
- for i in range(n - 1):
- min_index = i
- for j in range(i + 1, n):
- if arr[j] < arr[min_index]:
- min_index = j
- arr[min_index], arr[i] = arr[i], arr[min_index]
-
-
-arr = [26, 11, 99, 33, 69, 77, 55, 56, 67]
-selection_sort(arr)
-print(arr)
```
-## 算法分析
-
-空间复杂度 $O(1)$,时间复杂度 $O(n^2)$。
-
-那选择排序是稳定的排序算法吗?
-
-答案是否定的,**选择排序是一种不稳定的排序算法**。选择排序每次都要找剩余未排序元素中的最小值,并和前面的元素交换位置,这样破坏了稳定性。
-
-比如 5,8,5,2,9 这样一组数据,使用选择排序算法来排序的话,第一次找到最小元素 2,与第一个 5 交换位置,那第一个 5 和中间的 5 顺序就变了,所以就不稳定了。正是因此,相对于冒泡排序和插入排序,选择排序就稍微逊色了。
+
diff --git a/basic/sorting/ShellSort/README.md b/basic/sorting/ShellSort/README.md
index 80695c4934567..a357572f3440e 100644
--- a/basic/sorting/ShellSort/README.md
+++ b/basic/sorting/ShellSort/README.md
@@ -11,8 +11,6 @@
-### **Java**
-
```java
import java.util.Arrays;
@@ -41,34 +39,6 @@ public class ShellSort {
}
```
-### **JavaScript**
-
-```js
-function shellSort(arr) {
- var len = arr.length;
- var gapSize = Math.floor(len / 2);
- while (gapSize > 0) {
- for (var i = gapSize; i < len; i++) {
- var temp = arr[i];
- var j = i;
-
- while (j >= gapSize && arr[j - gapSize] > temp) {
- arr[j] = arr[j - gapSize];
- j -= gapSize;
- }
- arr[j] = temp;
- }
- gapSize = Math.floor(gapSize / 2);
- }
- return arr;
-}
-
-let arr = [6, 3, 2, 1, 5];
-console.log(shellSort(arr));
-```
-
-### **Go**
-
```go
package main
@@ -94,8 +64,6 @@ func main() {
}
```
-### **Rust**
-
```rust
fn shell_sort(nums: &mut Vec) {
let n = nums.len();
@@ -121,15 +89,30 @@ fn main() {
}
```
-
-
-## 算法分析
+```js
+function shellSort(arr) {
+ var len = arr.length;
+ var gapSize = Math.floor(len / 2);
+ while (gapSize > 0) {
+ for (var i = gapSize; i < len; i++) {
+ var temp = arr[i];
+ var j = i;
-时间复杂度:
+ while (j >= gapSize && arr[j - gapSize] > temp) {
+ arr[j] = arr[j - gapSize];
+ j -= gapSize;
+ }
+ arr[j] = temp;
+ }
+ gapSize = Math.floor(gapSize / 2);
+ }
+ return arr;
+}
-希尔排序的时间性能取决于所取“增量”序列的函数,这涉及到一些数学上尚未解决的难题。但是有人通过大量的实验,给出了较好的结果:当 $n$ 较大时,比较和移动的次数约在 $n^{1.25}$ 到 ${1.6n}^{1.25}$ 之间。所以可以这样简单记忆:
+let arr = [6, 3, 2, 1, 5];
+console.log(shellSort(arr));
+```
-- 当 $n$ 较小时,希尔排序和插入排序相差不大,都为 $n^2$ 左右。
-- 当 $n$ 很大时,时间增长幅度逐渐放缓,平均复杂度是 $O(n\log n)$。
+
-空间复杂度:$O(1)$。
+
diff --git a/lcci/01.01.Is Unique/README.md b/lcci/01.01.Is Unique/README.md
index 27083b6e429e2..8b2e953a68544 100644
--- a/lcci/01.01.Is Unique/README.md
+++ b/lcci/01.01.Is Unique/README.md
@@ -27,9 +27,7 @@
## 解法
-
-
-**方法一:位运算**
+### 方法一:位运算
根据示例,可以假定字符串中只包含小写字母(实际验证,也符合假设)。
@@ -39,10 +37,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def isUnique(self, astr: str) -> bool:
@@ -55,10 +49,6 @@ class Solution:
return True
```
-### **Java**
-
-
-
```java
class Solution {
public boolean isUnique(String astr) {
@@ -75,8 +65,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -94,8 +82,6 @@ public:
};
```
-### **Go**
-
```go
func isUnique(astr string) bool {
mask := 0
@@ -110,7 +96,19 @@ func isUnique(astr string) bool {
}
```
-### **JavaScript**
+```ts
+function isUnique(astr: string): boolean {
+ let mask = 0;
+ for (let j = 0; j < astr.length; ++j) {
+ const i = astr.charCodeAt(j) - 'a'.charCodeAt(0);
+ if ((mask >> i) & 1) {
+ return false;
+ }
+ mask |= 1 << i;
+ }
+ return true;
+}
+```
```js
/**
@@ -130,26 +128,6 @@ var isUnique = function (astr) {
};
```
-### **TypeScript**
-
-```ts
-function isUnique(astr: string): boolean {
- let mask = 0;
- for (let j = 0; j < astr.length; ++j) {
- const i = astr.charCodeAt(j) - 'a'.charCodeAt(0);
- if ((mask >> i) & 1) {
- return false;
- }
- mask |= 1 << i;
- }
- return true;
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.01.Is Unique/README_EN.md b/lcci/01.01.Is Unique/README_EN.md
index 4ef688cf36a24..a241a5f93ede1 100644
--- a/lcci/01.01.Is Unique/README_EN.md
+++ b/lcci/01.01.Is Unique/README_EN.md
@@ -34,7 +34,7 @@
## Solutions
-**Solution 1: Bit Manipulation**
+### Solution 1: Bit Manipulation
Based on the examples, we can assume that the string only contains lowercase letters (which is confirmed by actual verification).
@@ -44,8 +44,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space
-### **Python3**
-
```python
class Solution:
def isUnique(self, astr: str) -> bool:
@@ -58,8 +56,6 @@ class Solution:
return True
```
-### **Java**
-
```java
class Solution {
public boolean isUnique(String astr) {
@@ -76,8 +72,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -95,8 +89,6 @@ public:
};
```
-### **Go**
-
```go
func isUnique(astr string) bool {
mask := 0
@@ -111,7 +103,19 @@ func isUnique(astr string) bool {
}
```
-### **JavaScript**
+```ts
+function isUnique(astr: string): boolean {
+ let mask = 0;
+ for (let j = 0; j < astr.length; ++j) {
+ const i = astr.charCodeAt(j) - 'a'.charCodeAt(0);
+ if ((mask >> i) & 1) {
+ return false;
+ }
+ mask |= 1 << i;
+ }
+ return true;
+}
+```
```js
/**
@@ -131,26 +135,6 @@ var isUnique = function (astr) {
};
```
-### **TypeScript**
-
-```ts
-function isUnique(astr: string): boolean {
- let mask = 0;
- for (let j = 0; j < astr.length; ++j) {
- const i = astr.charCodeAt(j) - 'a'.charCodeAt(0);
- if ((mask >> i) & 1) {
- return false;
- }
- mask |= 1 << i;
- }
- return true;
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.02.Check Permutation/README.md b/lcci/01.02.Check Permutation/README.md
index c9e985a026b62..3b2f436ba7301 100644
--- a/lcci/01.02.Check Permutation/README.md
+++ b/lcci/01.02.Check Permutation/README.md
@@ -28,9 +28,7 @@
## 解法
-
-
-**方法一:数组或哈希表**
+### 方法一:数组或哈希表
我们先判断两个字符串的长度是否相等,若不相等则直接返回 `false`。
@@ -44,34 +42,14 @@
时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为字符串的长度,而 $C$ 为字符集的大小,本题 $C=26$。
-**方法二:排序**
-
-我们也按照字典序对两个字符串进行排序,然后比较两个字符串是否相等。
-
-时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。
-
-### **Python3**
-
-
-
```python
class Solution:
def CheckPermutation(self, s1: str, s2: str) -> bool:
return Counter(s1) == Counter(s2)
```
-```python
-class Solution:
- def CheckPermutation(self, s1: str, s2: str) -> bool:
- return sorted(s1) == sorted(s2)
-```
-
-### **Java**
-
-
-
```java
class Solution {
public boolean CheckPermutation(String s1, String s2) {
@@ -92,20 +70,6 @@ class Solution {
}
```
-```java
-class Solution {
- public boolean CheckPermutation(String s1, String s2) {
- char[] cs1 = s1.toCharArray();
- char[] cs2 = s2.toCharArray();
- Arrays.sort(cs1);
- Arrays.sort(cs2);
- return Arrays.equals(cs1, cs2);
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -120,19 +84,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- bool CheckPermutation(string s1, string s2) {
- sort(s1.begin(), s1.end());
- sort(s2.begin(), s2.end());
- return s1 == s2;
- }
-};
-```
-
-### **Go**
-
```go
func CheckPermutation(s1 string, s2 string) bool {
if len(s1) != len(s2) {
@@ -152,44 +103,6 @@ func CheckPermutation(s1 string, s2 string) bool {
}
```
-```go
-func CheckPermutation(s1 string, s2 string) bool {
- cs1, cs2 := []byte(s1), []byte(s2)
- sort.Slice(cs1, func(i, j int) bool { return cs1[i] < cs1[j] })
- sort.Slice(cs2, func(i, j int) bool { return cs2[i] < cs2[j] })
- return string(cs1) == string(cs2)
-}
-```
-
-### **JavaScript**
-
-```js
-/**
- * @param {string} s1
- * @param {string} s2
- * @return {boolean}
- */
-var CheckPermutation = function (s1, s2) {
- if (s1.length != s2.length) {
- return false;
- }
- const cnt = new Array(26).fill(0);
- for (let i = 0; i < s1.length; ++i) {
- const j = s1.codePointAt(i) - 'a'.codePointAt(0);
- ++cnt[j];
- }
- for (let i = 0; i < s2.length; ++i) {
- const j = s2.codePointAt(i) - 'a'.codePointAt(0);
- if (--cnt[j] < 0) {
- return false;
- }
- }
- return true;
-};
-```
-
-### **TypeScript**
-
```ts
function CheckPermutation(s1: string, s2: string): boolean {
const n = s1.length;
@@ -211,14 +124,6 @@ function CheckPermutation(s1: string, s2: string): boolean {
}
```
-```ts
-function CheckPermutation(s1: string, s2: string): boolean {
- return [...s1].sort().join('') === [...s2].sort().join('');
-}
-```
-
-### **Rust**
-
```rust
use std::collections::HashMap;
impl Solution {
@@ -240,6 +145,85 @@ impl Solution {
}
```
+```js
+/**
+ * @param {string} s1
+ * @param {string} s2
+ * @return {boolean}
+ */
+var CheckPermutation = function (s1, s2) {
+ if (s1.length != s2.length) {
+ return false;
+ }
+ const cnt = new Array(26).fill(0);
+ for (let i = 0; i < s1.length; ++i) {
+ const j = s1.codePointAt(i) - 'a'.codePointAt(0);
+ ++cnt[j];
+ }
+ for (let i = 0; i < s2.length; ++i) {
+ const j = s2.codePointAt(i) - 'a'.codePointAt(0);
+ if (--cnt[j] < 0) {
+ return false;
+ }
+ }
+ return true;
+};
+```
+
+
+
+### 方法二:排序
+
+我们也按照字典序对两个字符串进行排序,然后比较两个字符串是否相等。
+
+时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。
+
+
+
+```python
+class Solution:
+ def CheckPermutation(self, s1: str, s2: str) -> bool:
+ return sorted(s1) == sorted(s2)
+```
+
+```java
+class Solution {
+ public boolean CheckPermutation(String s1, String s2) {
+ char[] cs1 = s1.toCharArray();
+ char[] cs2 = s2.toCharArray();
+ Arrays.sort(cs1);
+ Arrays.sort(cs2);
+ return Arrays.equals(cs1, cs2);
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ bool CheckPermutation(string s1, string s2) {
+ sort(s1.begin(), s1.end());
+ sort(s2.begin(), s2.end());
+ return s1 == s2;
+ }
+};
+```
+
+```go
+func CheckPermutation(s1 string, s2 string) bool {
+ cs1, cs2 := []byte(s1), []byte(s2)
+ sort.Slice(cs1, func(i, j int) bool { return cs1[i] < cs1[j] })
+ sort.Slice(cs2, func(i, j int) bool { return cs2[i] < cs2[j] })
+ return string(cs1) == string(cs2)
+}
+```
+
+```ts
+function CheckPermutation(s1: string, s2: string): boolean {
+ return [...s1].sort().join('') === [...s2].sort().join('');
+}
+```
+
```rust
impl Solution {
pub fn check_permutation(s1: String, s2: String) -> bool {
@@ -252,10 +236,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.02.Check Permutation/README_EN.md b/lcci/01.02.Check Permutation/README_EN.md
index f8bdf236e751f..820dc97b1db2b 100644
--- a/lcci/01.02.Check Permutation/README_EN.md
+++ b/lcci/01.02.Check Permutation/README_EN.md
@@ -34,7 +34,7 @@
## Solutions
-**Solution 1: Array or Hash Table**
+### Solution 1: Array or Hash Table
First, we check whether the lengths of the two strings are equal. If they are not equal, we directly return `false`.
@@ -48,30 +48,14 @@ Note: In this problem, all test case strings only contain lowercase letters, so
The time complexity is $O(n)$, 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$.
-**Solution 2: Sorting**
-
-We can also sort the two strings in lexicographical order, and then compare whether the two strings are equal.
-
-The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string.
-
-### **Python3**
-
```python
class Solution:
def CheckPermutation(self, s1: str, s2: str) -> bool:
return Counter(s1) == Counter(s2)
```
-```python
-class Solution:
- def CheckPermutation(self, s1: str, s2: str) -> bool:
- return sorted(s1) == sorted(s2)
-```
-
-### **Java**
-
```java
class Solution {
public boolean CheckPermutation(String s1, String s2) {
@@ -92,20 +76,6 @@ class Solution {
}
```
-```java
-class Solution {
- public boolean CheckPermutation(String s1, String s2) {
- char[] cs1 = s1.toCharArray();
- char[] cs2 = s2.toCharArray();
- Arrays.sort(cs1);
- Arrays.sort(cs2);
- return Arrays.equals(cs1, cs2);
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -120,19 +90,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- bool CheckPermutation(string s1, string s2) {
- sort(s1.begin(), s1.end());
- sort(s2.begin(), s2.end());
- return s1 == s2;
- }
-};
-```
-
-### **Go**
-
```go
func CheckPermutation(s1 string, s2 string) bool {
if len(s1) != len(s2) {
@@ -152,44 +109,6 @@ func CheckPermutation(s1 string, s2 string) bool {
}
```
-```go
-func CheckPermutation(s1 string, s2 string) bool {
- cs1, cs2 := []byte(s1), []byte(s2)
- sort.Slice(cs1, func(i, j int) bool { return cs1[i] < cs1[j] })
- sort.Slice(cs2, func(i, j int) bool { return cs2[i] < cs2[j] })
- return string(cs1) == string(cs2)
-}
-```
-
-### **JavaScript**
-
-```js
-/**
- * @param {string} s1
- * @param {string} s2
- * @return {boolean}
- */
-var CheckPermutation = function (s1, s2) {
- if (s1.length != s2.length) {
- return false;
- }
- const cnt = new Array(26).fill(0);
- for (let i = 0; i < s1.length; ++i) {
- const j = s1.codePointAt(i) - 'a'.codePointAt(0);
- ++cnt[j];
- }
- for (let i = 0; i < s2.length; ++i) {
- const j = s2.codePointAt(i) - 'a'.codePointAt(0);
- if (--cnt[j] < 0) {
- return false;
- }
- }
- return true;
-};
-```
-
-### **TypeScript**
-
```ts
function CheckPermutation(s1: string, s2: string): boolean {
const n = s1.length;
@@ -211,14 +130,6 @@ function CheckPermutation(s1: string, s2: string): boolean {
}
```
-```ts
-function CheckPermutation(s1: string, s2: string): boolean {
- return [...s1].sort().join('') === [...s2].sort().join('');
-}
-```
-
-### **Rust**
-
```rust
use std::collections::HashMap;
impl Solution {
@@ -240,6 +151,85 @@ impl Solution {
}
```
+```js
+/**
+ * @param {string} s1
+ * @param {string} s2
+ * @return {boolean}
+ */
+var CheckPermutation = function (s1, s2) {
+ if (s1.length != s2.length) {
+ return false;
+ }
+ const cnt = new Array(26).fill(0);
+ for (let i = 0; i < s1.length; ++i) {
+ const j = s1.codePointAt(i) - 'a'.codePointAt(0);
+ ++cnt[j];
+ }
+ for (let i = 0; i < s2.length; ++i) {
+ const j = s2.codePointAt(i) - 'a'.codePointAt(0);
+ if (--cnt[j] < 0) {
+ return false;
+ }
+ }
+ return true;
+};
+```
+
+
+
+### Solution 2: Sorting
+
+We can also sort the two strings in lexicographical order, and then compare whether the two strings are equal.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string.
+
+
+
+```python
+class Solution:
+ def CheckPermutation(self, s1: str, s2: str) -> bool:
+ return sorted(s1) == sorted(s2)
+```
+
+```java
+class Solution {
+ public boolean CheckPermutation(String s1, String s2) {
+ char[] cs1 = s1.toCharArray();
+ char[] cs2 = s2.toCharArray();
+ Arrays.sort(cs1);
+ Arrays.sort(cs2);
+ return Arrays.equals(cs1, cs2);
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ bool CheckPermutation(string s1, string s2) {
+ sort(s1.begin(), s1.end());
+ sort(s2.begin(), s2.end());
+ return s1 == s2;
+ }
+};
+```
+
+```go
+func CheckPermutation(s1 string, s2 string) bool {
+ cs1, cs2 := []byte(s1), []byte(s2)
+ sort.Slice(cs1, func(i, j int) bool { return cs1[i] < cs1[j] })
+ sort.Slice(cs2, func(i, j int) bool { return cs2[i] < cs2[j] })
+ return string(cs1) == string(cs2)
+}
+```
+
+```ts
+function CheckPermutation(s1: string, s2: string): boolean {
+ return [...s1].sort().join('') === [...s2].sort().join('');
+}
+```
+
```rust
impl Solution {
pub fn check_permutation(s1: String, s2: String) -> bool {
@@ -252,10 +242,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.03.String to URL/README.md b/lcci/01.03.String to URL/README.md
index 053d57851e369..3dc83a075beec 100644
--- a/lcci/01.03.String to URL/README.md
+++ b/lcci/01.03.String to URL/README.md
@@ -27,40 +27,20 @@
## 解法
-
-
-**方法一:使用 `replace()` 函数**
+### 方法一:使用 `replace()` 函数
直接利用 `replace` 将所有 ` ` 替换为 `%20`:
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。
-**方法二:模拟**
-
-遍历字符串每个字符 $c$,遇到空格则将 `%20` 添加到结果中,否则添加 $c$。
-
-时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。
-
-### **Python3**
-
```python
class Solution:
def replaceSpaces(self, S: str, length: int) -> str:
return S[:length].replace(' ', '%20')
```
-```python
-class Solution:
- def replaceSpaces(self, S: str, length: int) -> str:
- return ''.join(['%20' if c == ' ' else c for c in S[:length]])
-```
-
-### **Java**
-
-
-
```java
class Solution {
public String replaceSpaces(String S, int length) {
@@ -80,21 +60,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {string} S
- * @param {number} length
- * @return {string}
- */
-var replaceSpaces = function (S, length) {
- return encodeURI(S.substring(0, length));
-};
-```
-
-### **Go**
-
```go
func replaceSpaces(S string, length int) string {
// return url.PathEscape(S[:length])
@@ -115,16 +80,12 @@ func replaceSpaces(S string, length int) string {
}
```
-### **TypeScript**
-
```ts
function replaceSpaces(S: string, length: number): string {
return S.slice(0, length).replace(/\s/g, '%20');
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn replace_spaces(s: String, length: i32) -> String {
@@ -133,6 +94,33 @@ impl Solution {
}
```
+```js
+/**
+ * @param {string} S
+ * @param {number} length
+ * @return {string}
+ */
+var replaceSpaces = function (S, length) {
+ return encodeURI(S.substring(0, length));
+};
+```
+
+
+
+### 方法二:模拟
+
+遍历字符串每个字符 $c$,遇到空格则将 `%20` 添加到结果中,否则添加 $c$。
+
+时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。
+
+
+
+```python
+class Solution:
+ def replaceSpaces(self, S: str, length: int) -> str:
+ return ''.join(['%20' if c == ' ' else c for c in S[:length]])
+```
+
```rust
impl Solution {
pub fn replace_spaces(s: String, length: i32) -> String {
@@ -146,10 +134,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.03.String to URL/README_EN.md b/lcci/01.03.String to URL/README_EN.md
index b5998438bc100..2238c831f4b5d 100644
--- a/lcci/01.03.String to URL/README_EN.md
+++ b/lcci/01.03.String to URL/README_EN.md
@@ -40,36 +40,20 @@ The missing numbers are [5,6,8,...], hence the third missing number is 8.
## Solutions
-**Solution 1: Using `replace()` function**
+### Solution 1: Using `replace()` function
Directly use `replace` to replace all ` ` with `%20`:
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string.
-**Solution 2: Simulation**
-
-Traverse each character $c$ in the string. When encountering a space, add `%20` to the result, otherwise add $c$.
-
-The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string.
-
-### **Python3**
-
```python
class Solution:
def replaceSpaces(self, S: str, length: int) -> str:
return S[:length].replace(' ', '%20')
```
-```python
-class Solution:
- def replaceSpaces(self, S: str, length: int) -> str:
- return ''.join(['%20' if c == ' ' else c for c in S[:length]])
-```
-
-### **Java**
-
```java
class Solution {
public String replaceSpaces(String S, int length) {
@@ -89,21 +73,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {string} S
- * @param {number} length
- * @return {string}
- */
-var replaceSpaces = function (S, length) {
- return encodeURI(S.substring(0, length));
-};
-```
-
-### **Go**
-
```go
func replaceSpaces(S string, length int) string {
// return url.PathEscape(S[:length])
@@ -124,16 +93,12 @@ func replaceSpaces(S string, length int) string {
}
```
-### **TypeScript**
-
```ts
function replaceSpaces(S: string, length: number): string {
return S.slice(0, length).replace(/\s/g, '%20');
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn replace_spaces(s: String, length: i32) -> String {
@@ -142,6 +107,33 @@ impl Solution {
}
```
+```js
+/**
+ * @param {string} S
+ * @param {number} length
+ * @return {string}
+ */
+var replaceSpaces = function (S, length) {
+ return encodeURI(S.substring(0, length));
+};
+```
+
+
+
+### Solution 2: Simulation
+
+Traverse each character $c$ in the string. When encountering a space, add `%20` to the result, otherwise add $c$.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string.
+
+
+
+```python
+class Solution:
+ def replaceSpaces(self, S: str, length: int) -> str:
+ return ''.join(['%20' if c == ' ' else c for c in S[:length]])
+```
+
```rust
impl Solution {
pub fn replace_spaces(s: String, length: i32) -> String {
@@ -155,10 +147,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.04.Palindrome Permutation/README.md b/lcci/01.04.Palindrome Permutation/README.md
index 8bcc584048b09..34c7a377036b9 100644
--- a/lcci/01.04.Palindrome Permutation/README.md
+++ b/lcci/01.04.Palindrome Permutation/README.md
@@ -23,9 +23,7 @@
## 解法
-
-
-**方法一:哈希表**
+### 方法一:哈希表
我们用哈希表 $cnt$ 存储每个字符出现的次数。若次数为奇数的字符超过 $1$ 个,则不是回文排列。
@@ -33,10 +31,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
@@ -44,22 +38,6 @@ class Solution:
return sum(v & 1 for v in cnt.values()) < 2
```
-```python
-class Solution:
- def canPermutePalindrome(self, s: str) -> bool:
- vis = set()
- for c in s:
- if c in vis:
- vis.remove(c)
- else:
- vis.add(c)
- return len(vis) < 2
-```
-
-### **Java**
-
-
-
```java
class Solution {
public boolean canPermutePalindrome(String s) {
@@ -76,23 +54,6 @@ class Solution {
}
```
-```java
-class Solution {
- public boolean canPermutePalindrome(String s) {
- Set vis = new HashSet<>();
- for (int i = 0; i < s.length(); ++i) {
- char c = s.charAt(i);
- if (!vis.add(c)) {
- vis.remove(c);
- }
- }
- return vis.size() < 2;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -110,25 +71,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- bool canPermutePalindrome(string s) {
- unordered_set vis;
- for (auto& c : s) {
- if (vis.count(c)) {
- vis.erase(c);
- } else {
- vis.insert(c);
- }
- }
- return vis.size() < 2;
- }
-};
-```
-
-### **Go**
-
```go
func canPermutePalindrome(s string) bool {
vis := map[rune]bool{}
@@ -146,8 +88,6 @@ func canPermutePalindrome(s string) bool {
}
```
-### **TypeScript**
-
```ts
function canPermutePalindrome(s: string): boolean {
const set = new Set();
@@ -162,8 +102,6 @@ function canPermutePalindrome(s: string): boolean {
}
```
-### **Rust**
-
```rust
use std::collections::HashSet;
@@ -182,10 +120,56 @@ impl Solution {
}
```
-### **...**
+
+
+### 方法二
+
+
+```python
+class Solution:
+ def canPermutePalindrome(self, s: str) -> bool:
+ vis = set()
+ for c in s:
+ if c in vis:
+ vis.remove(c)
+ else:
+ vis.add(c)
+ return len(vis) < 2
```
+```java
+class Solution {
+ public boolean canPermutePalindrome(String s) {
+ Set vis = new HashSet<>();
+ for (int i = 0; i < s.length(); ++i) {
+ char c = s.charAt(i);
+ if (!vis.add(c)) {
+ vis.remove(c);
+ }
+ }
+ return vis.size() < 2;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ bool canPermutePalindrome(string s) {
+ unordered_set vis;
+ for (auto& c : s) {
+ if (vis.count(c)) {
+ vis.erase(c);
+ } else {
+ vis.insert(c);
+ }
+ }
+ return vis.size() < 2;
+ }
+};
```
+
+
diff --git a/lcci/01.04.Palindrome Permutation/README_EN.md b/lcci/01.04.Palindrome Permutation/README_EN.md
index 1065b23314301..e557f7a324db0 100644
--- a/lcci/01.04.Palindrome Permutation/README_EN.md
+++ b/lcci/01.04.Palindrome Permutation/README_EN.md
@@ -20,7 +20,7 @@
## Solutions
-**Solution 1: Hash Table**
+### Solution 1: Hash Table
We use a hash table $cnt$ to store the occurrence count of each character. If more than $1$ character has an odd count, then it is not a palindrome permutation.
@@ -28,8 +28,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is
-### **Python3**
-
```python
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
@@ -37,20 +35,6 @@ class Solution:
return sum(v & 1 for v in cnt.values()) < 2
```
-```python
-class Solution:
- def canPermutePalindrome(self, s: str) -> bool:
- vis = set()
- for c in s:
- if c in vis:
- vis.remove(c)
- else:
- vis.add(c)
- return len(vis) < 2
-```
-
-### **Java**
-
```java
class Solution {
public boolean canPermutePalindrome(String s) {
@@ -67,23 +51,6 @@ class Solution {
}
```
-```java
-class Solution {
- public boolean canPermutePalindrome(String s) {
- Set vis = new HashSet<>();
- for (int i = 0; i < s.length(); ++i) {
- char c = s.charAt(i);
- if (!vis.add(c)) {
- vis.remove(c);
- }
- }
- return vis.size() < 2;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -101,25 +68,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- bool canPermutePalindrome(string s) {
- unordered_set vis;
- for (auto& c : s) {
- if (vis.count(c)) {
- vis.erase(c);
- } else {
- vis.insert(c);
- }
- }
- return vis.size() < 2;
- }
-};
-```
-
-### **Go**
-
```go
func canPermutePalindrome(s string) bool {
vis := map[rune]bool{}
@@ -137,8 +85,6 @@ func canPermutePalindrome(s string) bool {
}
```
-### **TypeScript**
-
```ts
function canPermutePalindrome(s: string): boolean {
const set = new Set();
@@ -153,8 +99,6 @@ function canPermutePalindrome(s: string): boolean {
}
```
-### **Rust**
-
```rust
use std::collections::HashSet;
@@ -173,10 +117,56 @@ impl Solution {
}
```
-### **...**
+
+
+### Solution 2
+
+
+```python
+class Solution:
+ def canPermutePalindrome(self, s: str) -> bool:
+ vis = set()
+ for c in s:
+ if c in vis:
+ vis.remove(c)
+ else:
+ vis.add(c)
+ return len(vis) < 2
```
+```java
+class Solution {
+ public boolean canPermutePalindrome(String s) {
+ Set vis = new HashSet<>();
+ for (int i = 0; i < s.length(); ++i) {
+ char c = s.charAt(i);
+ if (!vis.add(c)) {
+ vis.remove(c);
+ }
+ }
+ return vis.size() < 2;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ bool canPermutePalindrome(string s) {
+ unordered_set vis;
+ for (auto& c : s) {
+ if (vis.count(c)) {
+ vis.erase(c);
+ } else {
+ vis.insert(c);
+ }
+ }
+ return vis.size() < 2;
+ }
+};
```
+
+
diff --git a/lcci/01.05.One Away/README.md b/lcci/01.05.One Away/README.md
index e94caa36a2a21..7f9317db7dd8c 100644
--- a/lcci/01.05.One Away/README.md
+++ b/lcci/01.05.One Away/README.md
@@ -28,9 +28,7 @@ second = "pal"
## 解法
-
-
-**方法一:分情况讨论 + 双指针**
+### 方法一:分情况讨论 + 双指针
我们将字符串 $first$ 和 $second$ 的长度记为 $m$ 和 $n$,不妨设 $m \geq n$。
@@ -44,10 +42,6 @@ second = "pal"
-### **Python3**
-
-
-
```python
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
@@ -68,10 +62,6 @@ class Solution:
return cnt < 2
```
-### **Java**
-
-
-
```java
class Solution {
public boolean oneEditAway(String first, String second) {
@@ -105,8 +95,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -141,8 +129,6 @@ public:
};
```
-### **Go**
-
```go
func oneEditAway(first string, second string) bool {
m, n := len(first), len(second)
@@ -174,8 +160,6 @@ func oneEditAway(first string, second string) bool {
}
```
-### **TypeScript**
-
```ts
function oneEditAway(first: string, second: string): boolean {
let m: number = first.length;
@@ -210,8 +194,6 @@ function oneEditAway(first: string, second: string): boolean {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn one_edit_away(first: String, second: String) -> bool {
@@ -241,10 +223,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.05.One Away/README_EN.md b/lcci/01.05.One Away/README_EN.md
index b7e65457e75e9..9456059ccdaff 100644
--- a/lcci/01.05.One Away/README_EN.md
+++ b/lcci/01.05.One Away/README_EN.md
@@ -36,7 +36,7 @@ second = "pal"
## Solutions
-**Solution 1: Case Discussion + Two Pointers**
+### Solution 1: Case Discussion + Two Pointers
We denote the lengths of strings $first$ and $second$ as $m$ and $n$, respectively, where $m \geq n$.
@@ -50,8 +50,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space
-### **Python3**
-
```python
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
@@ -72,8 +70,6 @@ class Solution:
return cnt < 2
```
-### **Java**
-
```java
class Solution {
public boolean oneEditAway(String first, String second) {
@@ -107,8 +103,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -143,8 +137,6 @@ public:
};
```
-### **Go**
-
```go
func oneEditAway(first string, second string) bool {
m, n := len(first), len(second)
@@ -176,8 +168,6 @@ func oneEditAway(first string, second string) bool {
}
```
-### **TypeScript**
-
```ts
function oneEditAway(first: string, second: string): boolean {
let m: number = first.length;
@@ -212,8 +202,6 @@ function oneEditAway(first: string, second: string): boolean {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn one_edit_away(first: String, second: String) -> bool {
@@ -243,10 +231,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.06.Compress String/README.md b/lcci/01.06.Compress String/README.md
index a0e275aac93d8..7018975f69f2f 100644
--- a/lcci/01.06.Compress String/README.md
+++ b/lcci/01.06.Compress String/README.md
@@ -30,9 +30,7 @@
## 解法
-
-
-**方法一:双指针**
+### 方法一:双指针
我们可以利用双指针找出每个连续字符的起始位置和结束位置,计算出连续字符的长度,然后将字符和长度拼接到字符串 $t$ 中。
@@ -42,10 +40,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def compressString(self, S: str) -> str:
@@ -53,24 +47,6 @@ class Solution:
return min(S, t, key=len)
```
-```python
-class Solution:
- def compressString(self, S: str) -> str:
- t = []
- i, n = 0, len(S)
- while i < n:
- j = i + 1
- while j < n and S[j] == S[i]:
- j += 1
- t.append(S[i] + str(j - i))
- i = j
- return min(S, "".join(t), key=len)
-```
-
-### **Java**
-
-
-
```java
class Solution {
public String compressString(String S) {
@@ -90,8 +66,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -112,8 +86,6 @@ public:
};
```
-### **Go**
-
```go
func compressString(S string) string {
n := len(S)
@@ -134,30 +106,6 @@ func compressString(S string) string {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {string} S
- * @return {string}
- */
-var compressString = function (S) {
- const n = S.length;
- const t = [];
- for (let i = 0; i < n; ) {
- let j = i + 1;
- while (j < n && S.charAt(j) === S.charAt(i)) {
- ++j;
- }
- t.push(S.charAt(i), j - i);
- i = j;
- }
- return t.length < n ? t.join('') : S;
-};
-```
-
-### **Rust**
-
```rust
impl Solution {
pub fn compress_string(s: String) -> String {
@@ -185,10 +133,46 @@ impl Solution {
}
```
-### **...**
-
+```js
+/**
+ * @param {string} S
+ * @return {string}
+ */
+var compressString = function (S) {
+ const n = S.length;
+ const t = [];
+ for (let i = 0; i < n; ) {
+ let j = i + 1;
+ while (j < n && S.charAt(j) === S.charAt(i)) {
+ ++j;
+ }
+ t.push(S.charAt(i), j - i);
+ i = j;
+ }
+ return t.length < n ? t.join('') : S;
+};
```
+
+
+### 方法二
+
+
+
+```python
+class Solution:
+ def compressString(self, S: str) -> str:
+ t = []
+ i, n = 0, len(S)
+ while i < n:
+ j = i + 1
+ while j < n and S[j] == S[i]:
+ j += 1
+ t.append(S[i] + str(j - i))
+ i = j
+ return min(S, "".join(t), key=len)
```
+
+
diff --git a/lcci/01.06.Compress String/README_EN.md b/lcci/01.06.Compress String/README_EN.md
index 5c8accb3017ed..bc76535775a71 100644
--- a/lcci/01.06.Compress String/README_EN.md
+++ b/lcci/01.06.Compress String/README_EN.md
@@ -36,7 +36,7 @@ The compressed string is "a1b2c2d1", which is longer than the original
## Solutions
-**Solution 1: Two Pointers**
+### Solution 1: Two Pointers
We can use two pointers to find the start and end positions of each consecutive character, calculate the length of the consecutive characters, and then append the character and length to the string $t$.
@@ -46,8 +46,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is
-### **Python3**
-
```python
class Solution:
def compressString(self, S: str) -> str:
@@ -55,22 +53,6 @@ class Solution:
return min(S, t, key=len)
```
-```python
-class Solution:
- def compressString(self, S: str) -> str:
- t = []
- i, n = 0, len(S)
- while i < n:
- j = i + 1
- while j < n and S[j] == S[i]:
- j += 1
- t.append(S[i] + str(j - i))
- i = j
- return min(S, "".join(t), key=len)
-```
-
-### **Java**
-
```java
class Solution {
public String compressString(String S) {
@@ -90,8 +72,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -112,8 +92,6 @@ public:
};
```
-### **Go**
-
```go
func compressString(S string) string {
n := len(S)
@@ -134,30 +112,6 @@ func compressString(S string) string {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {string} S
- * @return {string}
- */
-var compressString = function (S) {
- const n = S.length;
- const t = [];
- for (let i = 0; i < n; ) {
- let j = i + 1;
- while (j < n && S.charAt(j) === S.charAt(i)) {
- ++j;
- }
- t.push(S.charAt(i), j - i);
- i = j;
- }
- return t.length < n ? t.join('') : S;
-};
-```
-
-### **Rust**
-
```rust
impl Solution {
pub fn compress_string(s: String) -> String {
@@ -185,10 +139,46 @@ impl Solution {
}
```
-### **...**
-
+```js
+/**
+ * @param {string} S
+ * @return {string}
+ */
+var compressString = function (S) {
+ const n = S.length;
+ const t = [];
+ for (let i = 0; i < n; ) {
+ let j = i + 1;
+ while (j < n && S.charAt(j) === S.charAt(i)) {
+ ++j;
+ }
+ t.push(S.charAt(i), j - i);
+ i = j;
+ }
+ return t.length < n ? t.join('') : S;
+};
```
+
+
+### Solution 2
+
+
+
+```python
+class Solution:
+ def compressString(self, S: str) -> str:
+ t = []
+ i, n = 0, len(S)
+ while i < n:
+ j = i + 1
+ while j < n and S[j] == S[i]:
+ j += 1
+ t.append(S[i] + str(j - i))
+ i = j
+ return min(S, "".join(t), key=len)
```
+
+
diff --git a/lcci/01.07.Rotate Matrix/README.md b/lcci/01.07.Rotate Matrix/README.md
index 40c6c818acad3..5a12b7d78deb4 100644
--- a/lcci/01.07.Rotate Matrix/README.md
+++ b/lcci/01.07.Rotate Matrix/README.md
@@ -49,9 +49,7 @@
## 解法
-
-
-**方法一:原地翻转**
+### 方法一:原地翻转
根据题目要求,我们实际上需要将 $matrix[i][j]$ 旋转至 $matrix[j][n - i - 1]$。
@@ -61,10 +59,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
@@ -77,10 +71,6 @@ class Solution:
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
```
-### **Java**
-
-
-
```java
class Solution {
public void rotate(int[][] matrix) {
@@ -103,8 +93,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -124,8 +112,6 @@ public:
};
```
-### **Go**
-
```go
func rotate(matrix [][]int) {
n := len(matrix)
@@ -142,25 +128,6 @@ func rotate(matrix [][]int) {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number[][]} matrix
- * @return {void} Do not return anything, modify matrix in-place instead.
- */
-var rotate = function (matrix) {
- matrix.reverse();
- for (let i = 0; i < matrix.length; ++i) {
- for (let j = 0; j < i; ++j) {
- [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
- }
- }
-};
-```
-
-### **TypeScript**
-
```ts
/**
Do not return anything, modify matrix in-place instead.
@@ -177,32 +144,6 @@ function rotate(matrix: number[][]): void {
}
```
-### **C#**
-
-```cs
-public class Solution {
- public void Rotate(int[][] matrix) {
- int n = matrix.Length;
- for (int i = 0; i < n >> 1; ++i) {
- for (int j = 0; j < n; ++j) {
- int t = matrix[i][j];
- matrix[i][j] = matrix[n - i - 1][j];
- matrix[n - i - 1][j] = t;
- }
- }
- for (int i = 0; i < n; ++i) {
- for (int j = 0; j < i; ++j) {
- int t = matrix[i][j];
- matrix[i][j] = matrix[j][i];
- matrix[j][i] = t;
- }
- }
- }
-}
-```
-
-### **Rust**
-
```rust
impl Solution {
pub fn rotate(matrix: &mut Vec>) {
@@ -225,10 +166,43 @@ impl Solution {
}
```
-### **...**
-
+```js
+/**
+ * @param {number[][]} matrix
+ * @return {void} Do not return anything, modify matrix in-place instead.
+ */
+var rotate = function (matrix) {
+ matrix.reverse();
+ for (let i = 0; i < matrix.length; ++i) {
+ for (let j = 0; j < i; ++j) {
+ [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
+ }
+ }
+};
```
+```cs
+public class Solution {
+ public void Rotate(int[][] matrix) {
+ int n = matrix.Length;
+ for (int i = 0; i < n >> 1; ++i) {
+ for (int j = 0; j < n; ++j) {
+ int t = matrix[i][j];
+ matrix[i][j] = matrix[n - i - 1][j];
+ matrix[n - i - 1][j] = t;
+ }
+ }
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < i; ++j) {
+ int t = matrix[i][j];
+ matrix[i][j] = matrix[j][i];
+ matrix[j][i] = t;
+ }
+ }
+ }
+}
```
+
+
diff --git a/lcci/01.07.Rotate Matrix/README_EN.md b/lcci/01.07.Rotate Matrix/README_EN.md
index 76919c602c597..9b09740ef5e96 100644
--- a/lcci/01.07.Rotate Matrix/README_EN.md
+++ b/lcci/01.07.Rotate Matrix/README_EN.md
@@ -78,7 +78,7 @@ Rotate the matrix in place. It becomes:
## Solutions
-**Solution 1: In-place Rotation**
+### Solution 1: In-place Rotation
According to the problem requirements, we actually need to rotate $matrix[i][j]$ to $matrix[j][n - i - 1]$.
@@ -88,8 +88,6 @@ The time complexity is $O(n^2)$, where $n$ is the side length of the matrix. The
-### **Python3**
-
```python
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
@@ -102,8 +100,6 @@ class Solution:
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
```
-### **Java**
-
```java
class Solution {
public void rotate(int[][] matrix) {
@@ -126,8 +122,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -147,8 +141,6 @@ public:
};
```
-### **Go**
-
```go
func rotate(matrix [][]int) {
n := len(matrix)
@@ -165,25 +157,6 @@ func rotate(matrix [][]int) {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number[][]} matrix
- * @return {void} Do not return anything, modify matrix in-place instead.
- */
-var rotate = function (matrix) {
- matrix.reverse();
- for (let i = 0; i < matrix.length; ++i) {
- for (let j = 0; j < i; ++j) {
- [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
- }
- }
-};
-```
-
-### **TypeScript**
-
```ts
/**
Do not return anything, modify matrix in-place instead.
@@ -200,32 +173,6 @@ function rotate(matrix: number[][]): void {
}
```
-### **C#**
-
-```cs
-public class Solution {
- public void Rotate(int[][] matrix) {
- int n = matrix.Length;
- for (int i = 0; i < n >> 1; ++i) {
- for (int j = 0; j < n; ++j) {
- int t = matrix[i][j];
- matrix[i][j] = matrix[n - i - 1][j];
- matrix[n - i - 1][j] = t;
- }
- }
- for (int i = 0; i < n; ++i) {
- for (int j = 0; j < i; ++j) {
- int t = matrix[i][j];
- matrix[i][j] = matrix[j][i];
- matrix[j][i] = t;
- }
- }
- }
-}
-```
-
-### **Rust**
-
```rust
impl Solution {
pub fn rotate(matrix: &mut Vec>) {
@@ -248,10 +195,43 @@ impl Solution {
}
```
-### **...**
-
+```js
+/**
+ * @param {number[][]} matrix
+ * @return {void} Do not return anything, modify matrix in-place instead.
+ */
+var rotate = function (matrix) {
+ matrix.reverse();
+ for (let i = 0; i < matrix.length; ++i) {
+ for (let j = 0; j < i; ++j) {
+ [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
+ }
+ }
+};
```
+```cs
+public class Solution {
+ public void Rotate(int[][] matrix) {
+ int n = matrix.Length;
+ for (int i = 0; i < n >> 1; ++i) {
+ for (int j = 0; j < n; ++j) {
+ int t = matrix[i][j];
+ matrix[i][j] = matrix[n - i - 1][j];
+ matrix[n - i - 1][j] = t;
+ }
+ }
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < i; ++j) {
+ int t = matrix[i][j];
+ matrix[i][j] = matrix[j][i];
+ matrix[j][i] = t;
+ }
+ }
+ }
+}
```
+
+
diff --git a/lcci/01.08.Zero Matrix/README.md b/lcci/01.08.Zero Matrix/README.md
index 216985d14f3a0..9a29c719d5dde 100644
--- a/lcci/01.08.Zero Matrix/README.md
+++ b/lcci/01.08.Zero Matrix/README.md
@@ -43,9 +43,7 @@
## 解法
-
-
-**方法一:数组标记**
+### 方法一:数组标记
我们分别用数组 `rows` 和 `cols` 标记待清零的行和列。
@@ -53,20 +51,8 @@
时间复杂度 $O(m \times n)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。
-**方法二:原地标记**
-
-方法一中使用了额外的数组标记待清零的行和列,实际上我们也可以直接用矩阵的第一行和第一列来标记,不需要开辟额外的数组空间。
-
-由于第一行、第一列用来做标记,它们的值可能会因为标记而发生改变,因此,我们需要额外的变量 $i0$, $j0$ 来标记第一行、第一列是否需要被清零。
-
-时间复杂度 $O(m \times n)$,其中 $m$ 和 $n$ 分别为矩阵的行数和列数。空间复杂度 $O(1)$。
-
-### **Python3**
-
-
-
```python
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
@@ -83,32 +69,6 @@ class Solution:
matrix[i][j] = 0
```
-```python
-class Solution:
- def setZeroes(self, matrix: List[List[int]]) -> None:
- m, n = len(matrix), len(matrix[0])
- i0 = any(v == 0 for v in matrix[0])
- j0 = any(matrix[i][0] == 0 for i in range(m))
- for i in range(1, m):
- for j in range(1, n):
- if matrix[i][j] == 0:
- matrix[i][0] = matrix[0][j] = 0
- for i in range(1, m):
- for j in range(1, n):
- if matrix[i][0] == 0 or matrix[0][j] == 0:
- matrix[i][j] = 0
- if i0:
- for j in range(n):
- matrix[0][j] = 0
- if j0:
- for i in range(m):
- matrix[i][0] = 0
-```
-
-### **Java**
-
-
-
```java
class Solution {
public void setZeroes(int[][] matrix) {
@@ -134,54 +94,6 @@ class Solution {
}
```
-```java
-class Solution {
- public void setZeroes(int[][] matrix) {
- int m = matrix.length, n = matrix[0].length;
- boolean i0 = false, j0 = false;
- for (int j = 0; j < n; ++j) {
- if (matrix[0][j] == 0) {
- i0 = true;
- break;
- }
- }
- for (int i = 0; i < m; ++i) {
- if (matrix[i][0] == 0) {
- j0 = true;
- break;
- }
- }
- for (int i = 1; i < m; ++i) {
- for (int j = 1; j < n; ++j) {
- if (matrix[i][j] == 0) {
- matrix[i][0] = 0;
- matrix[0][j] = 0;
- }
- }
- }
- for (int i = 1; i < m; ++i) {
- for (int j = 1; j < n; ++j) {
- if (matrix[i][0] == 0 || matrix[0][j] == 0) {
- matrix[i][j] = 0;
- }
- }
- }
- if (i0) {
- for (int j = 0; j < n; ++j) {
- matrix[0][j] = 0;
- }
- }
- if (j0) {
- for (int i = 0; i < m; ++i) {
- matrix[i][0] = 0;
- }
- }
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -208,55 +120,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- void setZeroes(vector>& matrix) {
- int m = matrix.size(), n = matrix[0].size();
- bool i0 = false, j0 = false;
- for (int j = 0; j < n; ++j) {
- if (matrix[0][j] == 0) {
- i0 = true;
- break;
- }
- }
- for (int i = 0; i < m; ++i) {
- if (matrix[i][0] == 0) {
- j0 = true;
- break;
- }
- }
- for (int i = 1; i < m; ++i) {
- for (int j = 1; j < n; ++j) {
- if (matrix[i][j] == 0) {
- matrix[i][0] = 0;
- matrix[0][j] = 0;
- }
- }
- }
- for (int i = 1; i < m; ++i) {
- for (int j = 1; j < n; ++j) {
- if (matrix[i][0] == 0 || matrix[0][j] == 0) {
- matrix[i][j] = 0;
- }
- }
- }
- if (i0) {
- for (int j = 0; j < n; ++j) {
- matrix[0][j] = 0;
- }
- }
- if (j0) {
- for (int i = 0; i < m; ++i) {
- matrix[i][0] = 0;
- }
- }
- }
-};
-```
-
-### **Go**
-
```go
func setZeroes(matrix [][]int) {
m, n := len(matrix), len(matrix[0])
@@ -280,77 +143,57 @@ func setZeroes(matrix [][]int) {
}
```
-```go
-func setZeroes(matrix [][]int) {
- m, n := len(matrix), len(matrix[0])
- i0, j0 := false, false
- for j := 0; j < n; j++ {
- if matrix[0][j] == 0 {
- i0 = true
- break
- }
- }
- for i := 0; i < m; i++ {
- if matrix[i][0] == 0 {
- j0 = true
- break
- }
- }
- for i := 1; i < m; i++ {
- for j := 1; j < n; j++ {
- if matrix[i][j] == 0 {
- matrix[i][0], matrix[0][j] = 0, 0
- }
- }
- }
- for i := 1; i < m; i++ {
- for j := 1; j < n; j++ {
- if matrix[i][0] == 0 || matrix[0][j] == 0 {
- matrix[i][j] = 0
- }
- }
- }
- if i0 {
- for j := 0; j < n; j++ {
- matrix[0][j] = 0
- }
- }
- if j0 {
- for i := 0; i < m; i++ {
- matrix[i][0] = 0
- }
- }
-}
-```
-
-### **JavaScript**
-
-```js
+```ts
/**
- * @param {number[][]} matrix
- * @return {void} Do not return anything, modify matrix in-place instead.
+ Do not return anything, modify matrix in-place instead.
*/
-var setZeroes = function (matrix) {
+function setZeroes(matrix: number[][]): void {
const m = matrix.length;
const n = matrix[0].length;
const rows = new Array(m).fill(false);
const cols = new Array(n).fill(false);
- for (let i = 0; i < m; ++i) {
- for (let j = 0; j < n; ++j) {
- if (matrix[i][j] == 0) {
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < n; j++) {
+ if (matrix[i][j] === 0) {
rows[i] = true;
cols[j] = true;
}
}
}
- for (let i = 0; i < m; ++i) {
- for (let j = 0; j < n; ++j) {
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < n; j++) {
if (rows[i] || cols[j]) {
matrix[i][j] = 0;
}
}
}
-};
+}
+```
+
+```rust
+impl Solution {
+ pub fn set_zeroes(matrix: &mut Vec>) {
+ let m = matrix.len();
+ let n = matrix[0].len();
+ let mut rows = vec![false; m];
+ let mut cols = vec![false; n];
+ for i in 0..m {
+ for j in 0..n {
+ if matrix[i][j] == 0 {
+ rows[i] = true;
+ cols[j] = true;
+ }
+ }
+ }
+ for i in 0..m {
+ for j in 0..n {
+ if rows[i] || cols[j] {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+ }
+}
```
```js
@@ -361,44 +204,26 @@ var setZeroes = function (matrix) {
var setZeroes = function (matrix) {
const m = matrix.length;
const n = matrix[0].length;
- let i0 = matrix[0].some(v => v == 0);
- let j0 = false;
+ const rows = new Array(m).fill(false);
+ const cols = new Array(n).fill(false);
for (let i = 0; i < m; ++i) {
- if (matrix[i][0] == 0) {
- j0 = true;
- break;
- }
- }
- for (let i = 1; i < m; ++i) {
- for (let j = 1; j < n; ++j) {
+ for (let j = 0; j < n; ++j) {
if (matrix[i][j] == 0) {
- matrix[i][0] = 0;
- matrix[0][j] = 0;
+ rows[i] = true;
+ cols[j] = true;
}
}
}
- for (let i = 1; i < m; ++i) {
- for (let j = 1; j < n; ++j) {
- if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ for (let i = 0; i < m; ++i) {
+ for (let j = 0; j < n; ++j) {
+ if (rows[i] || cols[j]) {
matrix[i][j] = 0;
}
}
}
- if (i0) {
- for (let j = 0; j < n; ++j) {
- matrix[0][j] = 0;
- }
- }
- if (j0) {
- for (let i = 0; i < m; ++i) {
- matrix[i][0] = 0;
- }
- }
};
```
-### **C**
-
```c
void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
int m = matrixSize;
@@ -427,78 +252,173 @@ void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
}
```
-```c
-void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
- int m = matrixSize;
- int n = matrixColSize[0];
- int l0 = 0;
- int r0 = 0;
- for (int i = 0; i < m; i++) {
- if (matrix[i][0] == 0) {
- l0 = 1;
- break;
+
+
+### 方法二:原地标记
+
+方法一中使用了额外的数组标记待清零的行和列,实际上我们也可以直接用矩阵的第一行和第一列来标记,不需要开辟额外的数组空间。
+
+由于第一行、第一列用来做标记,它们的值可能会因为标记而发生改变,因此,我们需要额外的变量 $i0$, $j0$ 来标记第一行、第一列是否需要被清零。
+
+时间复杂度 $O(m \times n)$,其中 $m$ 和 $n$ 分别为矩阵的行数和列数。空间复杂度 $O(1)$。
+
+
+
+```python
+class Solution:
+ def setZeroes(self, matrix: List[List[int]]) -> None:
+ m, n = len(matrix), len(matrix[0])
+ i0 = any(v == 0 for v in matrix[0])
+ j0 = any(matrix[i][0] == 0 for i in range(m))
+ for i in range(1, m):
+ for j in range(1, n):
+ if matrix[i][j] == 0:
+ matrix[i][0] = matrix[0][j] = 0
+ for i in range(1, m):
+ for j in range(1, n):
+ if matrix[i][0] == 0 or matrix[0][j] == 0:
+ matrix[i][j] = 0
+ if i0:
+ for j in range(n):
+ matrix[0][j] = 0
+ if j0:
+ for i in range(m):
+ matrix[i][0] = 0
+```
+
+```java
+class Solution {
+ public void setZeroes(int[][] matrix) {
+ int m = matrix.length, n = matrix[0].length;
+ boolean i0 = false, j0 = false;
+ for (int j = 0; j < n; ++j) {
+ if (matrix[0][j] == 0) {
+ i0 = true;
+ break;
+ }
}
- }
- for (int j = 0; j < n; j++) {
- if (matrix[0][j] == 0) {
- r0 = 1;
- break;
+ for (int i = 0; i < m; ++i) {
+ if (matrix[i][0] == 0) {
+ j0 = true;
+ break;
+ }
}
- }
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (matrix[i][j] == 0) {
- matrix[i][0] = 0;
- matrix[0][j] = 0;
+ for (int i = 1; i < m; ++i) {
+ for (int j = 1; j < n; ++j) {
+ if (matrix[i][j] == 0) {
+ matrix[i][0] = 0;
+ matrix[0][j] = 0;
+ }
}
}
- }
- for (int i = 1; i < m; i++) {
- for (int j = 1; j < n; j++) {
- if (matrix[i][0] == 0 || matrix[0][j] == 0) {
- matrix[i][j] = 0;
+ for (int i = 1; i < m; ++i) {
+ for (int j = 1; j < n; ++j) {
+ if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ matrix[i][j] = 0;
+ }
}
}
- }
- if (l0) {
- for (int i = 0; i < m; i++) {
- matrix[i][0] = 0;
+ if (i0) {
+ for (int j = 0; j < n; ++j) {
+ matrix[0][j] = 0;
+ }
}
- }
- if (r0) {
- for (int j = 0; j < n; j++) {
- matrix[0][j] = 0;
+ if (j0) {
+ for (int i = 0; i < m; ++i) {
+ matrix[i][0] = 0;
+ }
}
}
}
```
-### **TypeScript**
-
-```ts
-/**
- Do not return anything, modify matrix in-place instead.
- */
-function setZeroes(matrix: number[][]): void {
- const m = matrix.length;
- const n = matrix[0].length;
- const rows = new Array(m).fill(false);
- const cols = new Array(n).fill(false);
- for (let i = 0; i < m; i++) {
- for (let j = 0; j < n; j++) {
- if (matrix[i][j] === 0) {
- rows[i] = true;
- cols[j] = true;
+```cpp
+class Solution {
+public:
+ void setZeroes(vector>& matrix) {
+ int m = matrix.size(), n = matrix[0].size();
+ bool i0 = false, j0 = false;
+ for (int j = 0; j < n; ++j) {
+ if (matrix[0][j] == 0) {
+ i0 = true;
+ break;
}
}
- }
- for (let i = 0; i < m; i++) {
- for (let j = 0; j < n; j++) {
- if (rows[i] || cols[j]) {
- matrix[i][j] = 0;
+ for (int i = 0; i < m; ++i) {
+ if (matrix[i][0] == 0) {
+ j0 = true;
+ break;
+ }
+ }
+ for (int i = 1; i < m; ++i) {
+ for (int j = 1; j < n; ++j) {
+ if (matrix[i][j] == 0) {
+ matrix[i][0] = 0;
+ matrix[0][j] = 0;
+ }
+ }
+ }
+ for (int i = 1; i < m; ++i) {
+ for (int j = 1; j < n; ++j) {
+ if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+ if (i0) {
+ for (int j = 0; j < n; ++j) {
+ matrix[0][j] = 0;
+ }
+ }
+ if (j0) {
+ for (int i = 0; i < m; ++i) {
+ matrix[i][0] = 0;
}
}
}
+};
+```
+
+```go
+func setZeroes(matrix [][]int) {
+ m, n := len(matrix), len(matrix[0])
+ i0, j0 := false, false
+ for j := 0; j < n; j++ {
+ if matrix[0][j] == 0 {
+ i0 = true
+ break
+ }
+ }
+ for i := 0; i < m; i++ {
+ if matrix[i][0] == 0 {
+ j0 = true
+ break
+ }
+ }
+ for i := 1; i < m; i++ {
+ for j := 1; j < n; j++ {
+ if matrix[i][j] == 0 {
+ matrix[i][0], matrix[0][j] = 0, 0
+ }
+ }
+ }
+ for i := 1; i < m; i++ {
+ for j := 1; j < n; j++ {
+ if matrix[i][0] == 0 || matrix[0][j] == 0 {
+ matrix[i][j] = 0
+ }
+ }
+ }
+ if i0 {
+ for j := 0; j < n; j++ {
+ matrix[0][j] = 0
+ }
+ }
+ if j0 {
+ for i := 0; i < m; i++ {
+ matrix[i][0] = 0
+ }
+ }
}
```
@@ -551,34 +471,6 @@ function setZeroes(matrix: number[][]): void {
}
```
-### **Rust**
-
-```rust
-impl Solution {
- pub fn set_zeroes(matrix: &mut Vec>) {
- let m = matrix.len();
- let n = matrix[0].len();
- let mut rows = vec![false; m];
- let mut cols = vec![false; n];
- for i in 0..m {
- for j in 0..n {
- if matrix[i][j] == 0 {
- rows[i] = true;
- cols[j] = true;
- }
- }
- }
- for i in 0..m {
- for j in 0..n {
- if rows[i] || cols[j] {
- matrix[i][j] = 0;
- }
- }
- }
- }
-}
-```
-
```rust
impl Solution {
pub fn set_zeroes(matrix: &mut Vec>) {
@@ -633,10 +525,96 @@ impl Solution {
}
```
-### **...**
-
+```js
+/**
+ * @param {number[][]} matrix
+ * @return {void} Do not return anything, modify matrix in-place instead.
+ */
+var setZeroes = function (matrix) {
+ const m = matrix.length;
+ const n = matrix[0].length;
+ let i0 = matrix[0].some(v => v == 0);
+ let j0 = false;
+ for (let i = 0; i < m; ++i) {
+ if (matrix[i][0] == 0) {
+ j0 = true;
+ break;
+ }
+ }
+ for (let i = 1; i < m; ++i) {
+ for (let j = 1; j < n; ++j) {
+ if (matrix[i][j] == 0) {
+ matrix[i][0] = 0;
+ matrix[0][j] = 0;
+ }
+ }
+ }
+ for (let i = 1; i < m; ++i) {
+ for (let j = 1; j < n; ++j) {
+ if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+ if (i0) {
+ for (let j = 0; j < n; ++j) {
+ matrix[0][j] = 0;
+ }
+ }
+ if (j0) {
+ for (let i = 0; i < m; ++i) {
+ matrix[i][0] = 0;
+ }
+ }
+};
```
+```c
+void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
+ int m = matrixSize;
+ int n = matrixColSize[0];
+ int l0 = 0;
+ int r0 = 0;
+ for (int i = 0; i < m; i++) {
+ if (matrix[i][0] == 0) {
+ l0 = 1;
+ break;
+ }
+ }
+ for (int j = 0; j < n; j++) {
+ if (matrix[0][j] == 0) {
+ r0 = 1;
+ break;
+ }
+ }
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < n; j++) {
+ if (matrix[i][j] == 0) {
+ matrix[i][0] = 0;
+ matrix[0][j] = 0;
+ }
+ }
+ }
+ for (int i = 1; i < m; i++) {
+ for (int j = 1; j < n; j++) {
+ if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+ if (l0) {
+ for (int i = 0; i < m; i++) {
+ matrix[i][0] = 0;
+ }
+ }
+ if (r0) {
+ for (int j = 0; j < n; j++) {
+ matrix[0][j] = 0;
+ }
+ }
+}
```
+
+
diff --git a/lcci/01.08.Zero Matrix/README_EN.md b/lcci/01.08.Zero Matrix/README_EN.md
index 5a7ead1edc030..90bbd2ce546b5 100644
--- a/lcci/01.08.Zero Matrix/README_EN.md
+++ b/lcci/01.08.Zero Matrix/README_EN.md
@@ -70,7 +70,7 @@
## Solutions
-**Solution 1: Array Marking**
+### Solution 1: Array Marking
We use arrays `rows` and `cols` to mark the rows and columns to be zeroed.
@@ -78,18 +78,8 @@ Then we traverse the matrix again, zeroing the elements corresponding to the row
The time complexity is $O(m \times n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively.
-**Solution 2: In-place Marking**
-
-In Solution 1, we used additional arrays to mark the rows and columns to be zeroed. In fact, we can directly use the first row and first column of the matrix for marking, without needing to allocate additional array space.
-
-Since the first row and first column are used for marking, their values may change due to the marking. Therefore, we need additional variables $i0$ and $j0$ to mark whether the first row and first column need to be zeroed.
-
-The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$.
-
-### **Python3**
-
```python
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
@@ -106,30 +96,6 @@ class Solution:
matrix[i][j] = 0
```
-```python
-class Solution:
- def setZeroes(self, matrix: List[List[int]]) -> None:
- m, n = len(matrix), len(matrix[0])
- i0 = any(v == 0 for v in matrix[0])
- j0 = any(matrix[i][0] == 0 for i in range(m))
- for i in range(1, m):
- for j in range(1, n):
- if matrix[i][j] == 0:
- matrix[i][0] = matrix[0][j] = 0
- for i in range(1, m):
- for j in range(1, n):
- if matrix[i][0] == 0 or matrix[0][j] == 0:
- matrix[i][j] = 0
- if i0:
- for j in range(n):
- matrix[0][j] = 0
- if j0:
- for i in range(m):
- matrix[i][0] = 0
-```
-
-### **Java**
-
```java
class Solution {
public void setZeroes(int[][] matrix) {
@@ -155,54 +121,6 @@ class Solution {
}
```
-```java
-class Solution {
- public void setZeroes(int[][] matrix) {
- int m = matrix.length, n = matrix[0].length;
- boolean i0 = false, j0 = false;
- for (int j = 0; j < n; ++j) {
- if (matrix[0][j] == 0) {
- i0 = true;
- break;
- }
- }
- for (int i = 0; i < m; ++i) {
- if (matrix[i][0] == 0) {
- j0 = true;
- break;
- }
- }
- for (int i = 1; i < m; ++i) {
- for (int j = 1; j < n; ++j) {
- if (matrix[i][j] == 0) {
- matrix[i][0] = 0;
- matrix[0][j] = 0;
- }
- }
- }
- for (int i = 1; i < m; ++i) {
- for (int j = 1; j < n; ++j) {
- if (matrix[i][0] == 0 || matrix[0][j] == 0) {
- matrix[i][j] = 0;
- }
- }
- }
- if (i0) {
- for (int j = 0; j < n; ++j) {
- matrix[0][j] = 0;
- }
- }
- if (j0) {
- for (int i = 0; i < m; ++i) {
- matrix[i][0] = 0;
- }
- }
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -229,55 +147,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- void setZeroes(vector>& matrix) {
- int m = matrix.size(), n = matrix[0].size();
- bool i0 = false, j0 = false;
- for (int j = 0; j < n; ++j) {
- if (matrix[0][j] == 0) {
- i0 = true;
- break;
- }
- }
- for (int i = 0; i < m; ++i) {
- if (matrix[i][0] == 0) {
- j0 = true;
- break;
- }
- }
- for (int i = 1; i < m; ++i) {
- for (int j = 1; j < n; ++j) {
- if (matrix[i][j] == 0) {
- matrix[i][0] = 0;
- matrix[0][j] = 0;
- }
- }
- }
- for (int i = 1; i < m; ++i) {
- for (int j = 1; j < n; ++j) {
- if (matrix[i][0] == 0 || matrix[0][j] == 0) {
- matrix[i][j] = 0;
- }
- }
- }
- if (i0) {
- for (int j = 0; j < n; ++j) {
- matrix[0][j] = 0;
- }
- }
- if (j0) {
- for (int i = 0; i < m; ++i) {
- matrix[i][0] = 0;
- }
- }
- }
-};
-```
-
-### **Go**
-
```go
func setZeroes(matrix [][]int) {
m, n := len(matrix), len(matrix[0])
@@ -301,77 +170,57 @@ func setZeroes(matrix [][]int) {
}
```
-```go
-func setZeroes(matrix [][]int) {
- m, n := len(matrix), len(matrix[0])
- i0, j0 := false, false
- for j := 0; j < n; j++ {
- if matrix[0][j] == 0 {
- i0 = true
- break
- }
- }
- for i := 0; i < m; i++ {
- if matrix[i][0] == 0 {
- j0 = true
- break
- }
- }
- for i := 1; i < m; i++ {
- for j := 1; j < n; j++ {
- if matrix[i][j] == 0 {
- matrix[i][0], matrix[0][j] = 0, 0
- }
- }
- }
- for i := 1; i < m; i++ {
- for j := 1; j < n; j++ {
- if matrix[i][0] == 0 || matrix[0][j] == 0 {
- matrix[i][j] = 0
- }
- }
- }
- if i0 {
- for j := 0; j < n; j++ {
- matrix[0][j] = 0
- }
- }
- if j0 {
- for i := 0; i < m; i++ {
- matrix[i][0] = 0
- }
- }
-}
-```
-
-### **JavaScript**
-
-```js
+```ts
/**
- * @param {number[][]} matrix
- * @return {void} Do not return anything, modify matrix in-place instead.
+ Do not return anything, modify matrix in-place instead.
*/
-var setZeroes = function (matrix) {
+function setZeroes(matrix: number[][]): void {
const m = matrix.length;
const n = matrix[0].length;
const rows = new Array(m).fill(false);
const cols = new Array(n).fill(false);
- for (let i = 0; i < m; ++i) {
- for (let j = 0; j < n; ++j) {
- if (matrix[i][j] == 0) {
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < n; j++) {
+ if (matrix[i][j] === 0) {
rows[i] = true;
cols[j] = true;
}
}
}
- for (let i = 0; i < m; ++i) {
- for (let j = 0; j < n; ++j) {
+ for (let i = 0; i < m; i++) {
+ for (let j = 0; j < n; j++) {
if (rows[i] || cols[j]) {
matrix[i][j] = 0;
}
}
}
-};
+}
+```
+
+```rust
+impl Solution {
+ pub fn set_zeroes(matrix: &mut Vec>) {
+ let m = matrix.len();
+ let n = matrix[0].len();
+ let mut rows = vec![false; m];
+ let mut cols = vec![false; n];
+ for i in 0..m {
+ for j in 0..n {
+ if matrix[i][j] == 0 {
+ rows[i] = true;
+ cols[j] = true;
+ }
+ }
+ }
+ for i in 0..m {
+ for j in 0..n {
+ if rows[i] || cols[j] {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+ }
+}
```
```js
@@ -382,44 +231,26 @@ var setZeroes = function (matrix) {
var setZeroes = function (matrix) {
const m = matrix.length;
const n = matrix[0].length;
- let i0 = matrix[0].some(v => v == 0);
- let j0 = false;
+ const rows = new Array(m).fill(false);
+ const cols = new Array(n).fill(false);
for (let i = 0; i < m; ++i) {
- if (matrix[i][0] == 0) {
- j0 = true;
- break;
- }
- }
- for (let i = 1; i < m; ++i) {
- for (let j = 1; j < n; ++j) {
+ for (let j = 0; j < n; ++j) {
if (matrix[i][j] == 0) {
- matrix[i][0] = 0;
- matrix[0][j] = 0;
+ rows[i] = true;
+ cols[j] = true;
}
}
}
- for (let i = 1; i < m; ++i) {
- for (let j = 1; j < n; ++j) {
- if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ for (let i = 0; i < m; ++i) {
+ for (let j = 0; j < n; ++j) {
+ if (rows[i] || cols[j]) {
matrix[i][j] = 0;
}
}
}
- if (i0) {
- for (let j = 0; j < n; ++j) {
- matrix[0][j] = 0;
- }
- }
- if (j0) {
- for (let i = 0; i < m; ++i) {
- matrix[i][0] = 0;
- }
- }
};
```
-### **C**
-
```c
void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
int m = matrixSize;
@@ -448,78 +279,173 @@ void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
}
```
-```c
-void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
- int m = matrixSize;
- int n = matrixColSize[0];
- int l0 = 0;
- int r0 = 0;
- for (int i = 0; i < m; i++) {
- if (matrix[i][0] == 0) {
- l0 = 1;
- break;
+
+
+### Solution 2: In-place Marking
+
+In Solution 1, we used additional arrays to mark the rows and columns to be zeroed. In fact, we can directly use the first row and first column of the matrix for marking, without needing to allocate additional array space.
+
+Since the first row and first column are used for marking, their values may change due to the marking. Therefore, we need additional variables $i0$ and $j0$ to mark whether the first row and first column need to be zeroed.
+
+The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$.
+
+
+
+```python
+class Solution:
+ def setZeroes(self, matrix: List[List[int]]) -> None:
+ m, n = len(matrix), len(matrix[0])
+ i0 = any(v == 0 for v in matrix[0])
+ j0 = any(matrix[i][0] == 0 for i in range(m))
+ for i in range(1, m):
+ for j in range(1, n):
+ if matrix[i][j] == 0:
+ matrix[i][0] = matrix[0][j] = 0
+ for i in range(1, m):
+ for j in range(1, n):
+ if matrix[i][0] == 0 or matrix[0][j] == 0:
+ matrix[i][j] = 0
+ if i0:
+ for j in range(n):
+ matrix[0][j] = 0
+ if j0:
+ for i in range(m):
+ matrix[i][0] = 0
+```
+
+```java
+class Solution {
+ public void setZeroes(int[][] matrix) {
+ int m = matrix.length, n = matrix[0].length;
+ boolean i0 = false, j0 = false;
+ for (int j = 0; j < n; ++j) {
+ if (matrix[0][j] == 0) {
+ i0 = true;
+ break;
+ }
}
- }
- for (int j = 0; j < n; j++) {
- if (matrix[0][j] == 0) {
- r0 = 1;
- break;
+ for (int i = 0; i < m; ++i) {
+ if (matrix[i][0] == 0) {
+ j0 = true;
+ break;
+ }
}
- }
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- if (matrix[i][j] == 0) {
- matrix[i][0] = 0;
- matrix[0][j] = 0;
+ for (int i = 1; i < m; ++i) {
+ for (int j = 1; j < n; ++j) {
+ if (matrix[i][j] == 0) {
+ matrix[i][0] = 0;
+ matrix[0][j] = 0;
+ }
}
}
- }
- for (int i = 1; i < m; i++) {
- for (int j = 1; j < n; j++) {
- if (matrix[i][0] == 0 || matrix[0][j] == 0) {
- matrix[i][j] = 0;
+ for (int i = 1; i < m; ++i) {
+ for (int j = 1; j < n; ++j) {
+ if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ matrix[i][j] = 0;
+ }
}
}
- }
- if (l0) {
- for (int i = 0; i < m; i++) {
- matrix[i][0] = 0;
+ if (i0) {
+ for (int j = 0; j < n; ++j) {
+ matrix[0][j] = 0;
+ }
}
- }
- if (r0) {
- for (int j = 0; j < n; j++) {
- matrix[0][j] = 0;
+ if (j0) {
+ for (int i = 0; i < m; ++i) {
+ matrix[i][0] = 0;
+ }
}
}
}
```
-### **TypeScript**
-
-```ts
-/**
- Do not return anything, modify matrix in-place instead.
- */
-function setZeroes(matrix: number[][]): void {
- const m = matrix.length;
- const n = matrix[0].length;
- const rows = new Array(m).fill(false);
- const cols = new Array(n).fill(false);
- for (let i = 0; i < m; i++) {
- for (let j = 0; j < n; j++) {
- if (matrix[i][j] === 0) {
- rows[i] = true;
- cols[j] = true;
+```cpp
+class Solution {
+public:
+ void setZeroes(vector>& matrix) {
+ int m = matrix.size(), n = matrix[0].size();
+ bool i0 = false, j0 = false;
+ for (int j = 0; j < n; ++j) {
+ if (matrix[0][j] == 0) {
+ i0 = true;
+ break;
}
}
- }
- for (let i = 0; i < m; i++) {
- for (let j = 0; j < n; j++) {
- if (rows[i] || cols[j]) {
- matrix[i][j] = 0;
+ for (int i = 0; i < m; ++i) {
+ if (matrix[i][0] == 0) {
+ j0 = true;
+ break;
+ }
+ }
+ for (int i = 1; i < m; ++i) {
+ for (int j = 1; j < n; ++j) {
+ if (matrix[i][j] == 0) {
+ matrix[i][0] = 0;
+ matrix[0][j] = 0;
+ }
+ }
+ }
+ for (int i = 1; i < m; ++i) {
+ for (int j = 1; j < n; ++j) {
+ if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+ if (i0) {
+ for (int j = 0; j < n; ++j) {
+ matrix[0][j] = 0;
+ }
+ }
+ if (j0) {
+ for (int i = 0; i < m; ++i) {
+ matrix[i][0] = 0;
}
}
}
+};
+```
+
+```go
+func setZeroes(matrix [][]int) {
+ m, n := len(matrix), len(matrix[0])
+ i0, j0 := false, false
+ for j := 0; j < n; j++ {
+ if matrix[0][j] == 0 {
+ i0 = true
+ break
+ }
+ }
+ for i := 0; i < m; i++ {
+ if matrix[i][0] == 0 {
+ j0 = true
+ break
+ }
+ }
+ for i := 1; i < m; i++ {
+ for j := 1; j < n; j++ {
+ if matrix[i][j] == 0 {
+ matrix[i][0], matrix[0][j] = 0, 0
+ }
+ }
+ }
+ for i := 1; i < m; i++ {
+ for j := 1; j < n; j++ {
+ if matrix[i][0] == 0 || matrix[0][j] == 0 {
+ matrix[i][j] = 0
+ }
+ }
+ }
+ if i0 {
+ for j := 0; j < n; j++ {
+ matrix[0][j] = 0
+ }
+ }
+ if j0 {
+ for i := 0; i < m; i++ {
+ matrix[i][0] = 0
+ }
+ }
}
```
@@ -572,34 +498,6 @@ function setZeroes(matrix: number[][]): void {
}
```
-### **Rust**
-
-```rust
-impl Solution {
- pub fn set_zeroes(matrix: &mut Vec>) {
- let m = matrix.len();
- let n = matrix[0].len();
- let mut rows = vec![false; m];
- let mut cols = vec![false; n];
- for i in 0..m {
- for j in 0..n {
- if matrix[i][j] == 0 {
- rows[i] = true;
- cols[j] = true;
- }
- }
- }
- for i in 0..m {
- for j in 0..n {
- if rows[i] || cols[j] {
- matrix[i][j] = 0;
- }
- }
- }
- }
-}
-```
-
```rust
impl Solution {
pub fn set_zeroes(matrix: &mut Vec>) {
@@ -654,10 +552,96 @@ impl Solution {
}
```
-### **...**
-
+```js
+/**
+ * @param {number[][]} matrix
+ * @return {void} Do not return anything, modify matrix in-place instead.
+ */
+var setZeroes = function (matrix) {
+ const m = matrix.length;
+ const n = matrix[0].length;
+ let i0 = matrix[0].some(v => v == 0);
+ let j0 = false;
+ for (let i = 0; i < m; ++i) {
+ if (matrix[i][0] == 0) {
+ j0 = true;
+ break;
+ }
+ }
+ for (let i = 1; i < m; ++i) {
+ for (let j = 1; j < n; ++j) {
+ if (matrix[i][j] == 0) {
+ matrix[i][0] = 0;
+ matrix[0][j] = 0;
+ }
+ }
+ }
+ for (let i = 1; i < m; ++i) {
+ for (let j = 1; j < n; ++j) {
+ if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+ if (i0) {
+ for (let j = 0; j < n; ++j) {
+ matrix[0][j] = 0;
+ }
+ }
+ if (j0) {
+ for (let i = 0; i < m; ++i) {
+ matrix[i][0] = 0;
+ }
+ }
+};
```
+```c
+void setZeroes(int** matrix, int matrixSize, int* matrixColSize) {
+ int m = matrixSize;
+ int n = matrixColSize[0];
+ int l0 = 0;
+ int r0 = 0;
+ for (int i = 0; i < m; i++) {
+ if (matrix[i][0] == 0) {
+ l0 = 1;
+ break;
+ }
+ }
+ for (int j = 0; j < n; j++) {
+ if (matrix[0][j] == 0) {
+ r0 = 1;
+ break;
+ }
+ }
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < n; j++) {
+ if (matrix[i][j] == 0) {
+ matrix[i][0] = 0;
+ matrix[0][j] = 0;
+ }
+ }
+ }
+ for (int i = 1; i < m; i++) {
+ for (int j = 1; j < n; j++) {
+ if (matrix[i][0] == 0 || matrix[0][j] == 0) {
+ matrix[i][j] = 0;
+ }
+ }
+ }
+ if (l0) {
+ for (int i = 0; i < m; i++) {
+ matrix[i][0] = 0;
+ }
+ }
+ if (r0) {
+ for (int j = 0; j < n; j++) {
+ matrix[0][j] = 0;
+ }
+ }
+}
```
+
+
diff --git a/lcci/01.09.String Rotation/README.md b/lcci/01.09.String Rotation/README.md
index d6483f6561de4..35a96810b7d0d 100644
--- a/lcci/01.09.String Rotation/README.md
+++ b/lcci/01.09.String Rotation/README.md
@@ -36,9 +36,7 @@
## 解法
-
-
-**方法一:字符串匹配**
+### 方法一:字符串匹配
首先,如果字符串 $s1$ 和 $s2$ 长度不相等,那么肯定不是旋转字符串。
@@ -61,18 +59,12 @@ s1 + s1 = "abaaba"
-### **Python3**
-
```python
class Solution:
def isFlipedString(self, s1: str, s2: str) -> bool:
return len(s1) == len(s2) and s2 in s1 * 2
```
-### **Java**
-
-
-
```java
class Solution {
public boolean isFlipedString(String s1, String s2) {
@@ -81,8 +73,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -92,24 +82,18 @@ public:
};
```
-### **Go**
-
```go
func isFlipedString(s1 string, s2 string) bool {
return len(s1) == len(s2) && strings.Contains(s1+s1, s2)
}
```
-### **TypeScript**
-
```ts
function isFlipedString(s1: string, s2: string): boolean {
return s1.length === s2.length && (s2 + s2).indexOf(s1) !== -1;
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn is_fliped_string(s1: String, s2: String) -> bool {
@@ -118,7 +102,11 @@ impl Solution {
}
```
-原始写法:
+
+
+### 方法二
+
+
```rust
impl Solution {
@@ -149,10 +137,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/01.09.String Rotation/README_EN.md b/lcci/01.09.String Rotation/README_EN.md
index eb31c0a5ebe87..7cb3f64964478 100644
--- a/lcci/01.09.String Rotation/README_EN.md
+++ b/lcci/01.09.String Rotation/README_EN.md
@@ -36,7 +36,7 @@
## Solutions
-**Solution 1: String Matching**
+### Solution 1: String Matching
First, if the lengths of strings $s1$ and $s2$ are not equal, they are definitely not rotation strings of each other.
@@ -59,16 +59,12 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is
-### **Python3**
-
```python
class Solution:
def isFlipedString(self, s1: str, s2: str) -> bool:
return len(s1) == len(s2) and s2 in s1 * 2
```
-### **Java**
-
```java
class Solution {
public boolean isFlipedString(String s1, String s2) {
@@ -77,8 +73,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -88,24 +82,18 @@ public:
};
```
-### **Go**
-
```go
func isFlipedString(s1 string, s2 string) bool {
return len(s1) == len(s2) && strings.Contains(s1+s1, s2)
}
```
-### **TypeScript**
-
```ts
function isFlipedString(s1: string, s2: string): boolean {
return s1.length === s2.length && (s2 + s2).indexOf(s1) !== -1;
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn is_fliped_string(s1: String, s2: String) -> bool {
@@ -114,6 +102,12 @@ impl Solution {
}
```
+
+
+### Solution 2
+
+
+
```rust
impl Solution {
pub fn is_fliped_string(s1: String, s2: String) -> bool {
@@ -143,10 +137,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/02.01.Remove Duplicate Node/README.md b/lcci/02.01.Remove Duplicate Node/README.md
index dc8c14d1dede2..db19f23ba90bf 100644
--- a/lcci/02.01.Remove Duplicate Node/README.md
+++ b/lcci/02.01.Remove Duplicate Node/README.md
@@ -34,14 +34,10 @@
## 解法
-
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for singly-linked list.
# class ListNode:
@@ -67,10 +63,6 @@ class Solution:
return head
```
-### **Java**
-
-
-
```java
/**
* Definition for singly-linked list.
@@ -101,41 +93,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-/**
- * @param {ListNode} head
- * @return {ListNode}
- */
-var removeDuplicateNodes = function (head) {
- if (head == null || head.next == null) return head;
- const cache = new Set([]);
- cache.add(head.val);
- let cur = head,
- fast = head.next;
- while (fast !== null) {
- if (!cache.has(fast.val)) {
- cur.next = fast;
- cur = cur.next;
- cache.add(fast.val);
- }
- fast = fast.next;
- }
- cur.next = null;
- return head;
-};
-```
-
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -166,8 +123,6 @@ public:
};
```
-### **Go**
-
```go
func removeDuplicateNodes(head *ListNode) *ListNode {
if head == nil {
@@ -187,8 +142,6 @@ func removeDuplicateNodes(head *ListNode) *ListNode {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for singly-linked list.
@@ -220,40 +173,6 @@ function removeDuplicateNodes(head: ListNode | null): ListNode | null {
}
```
-暴力(不推荐)
-
-```ts
-/**
- * Definition for singly-linked list.
- * class ListNode {
- * val: number
- * next: ListNode | null
- * constructor(val?: number, next?: ListNode | null) {
- * this.val = (val===undefined ? 0 : val)
- * this.next = (next===undefined ? null : next)
- * }
- * }
- */
-
-function removeDuplicateNodes(head: ListNode | null): ListNode | null {
- let n1 = head;
- while (n1 != null) {
- let n2 = n1;
- while (n2.next != null) {
- if (n1.val === n2.next.val) {
- n2.next = n2.next.next;
- } else {
- n2 = n2.next;
- }
- }
- n1 = n1.next;
- }
- return head;
-}
-```
-
-### **Rust**
-
```rust
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
@@ -296,10 +215,73 @@ impl Solution {
}
```
-### **...**
-
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} head
+ * @return {ListNode}
+ */
+var removeDuplicateNodes = function (head) {
+ if (head == null || head.next == null) return head;
+ const cache = new Set([]);
+ cache.add(head.val);
+ let cur = head,
+ fast = head.next;
+ while (fast !== null) {
+ if (!cache.has(fast.val)) {
+ cur.next = fast;
+ cur = cur.next;
+ cache.add(fast.val);
+ }
+ fast = fast.next;
+ }
+ cur.next = null;
+ return head;
+};
```
+
+
+### 方法二
+
+
+
+```ts
+/**
+ * Definition for singly-linked list.
+ * class ListNode {
+ * val: number
+ * next: ListNode | null
+ * constructor(val?: number, next?: ListNode | null) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.next = (next===undefined ? null : next)
+ * }
+ * }
+ */
+
+function removeDuplicateNodes(head: ListNode | null): ListNode | null {
+ let n1 = head;
+ while (n1 != null) {
+ let n2 = n1;
+ while (n2.next != null) {
+ if (n1.val === n2.next.val) {
+ n2.next = n2.next.next;
+ } else {
+ n2 = n2.next;
+ }
+ }
+ n1 = n1.next;
+ }
+ return head;
+}
```
+
+
diff --git a/lcci/02.01.Remove Duplicate Node/README_EN.md b/lcci/02.01.Remove Duplicate Node/README_EN.md
index 98e3c108d3494..4b43fc5a15003 100644
--- a/lcci/02.01.Remove Duplicate Node/README_EN.md
+++ b/lcci/02.01.Remove Duplicate Node/README_EN.md
@@ -39,9 +39,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for singly-linked list.
@@ -68,8 +68,6 @@ class Solution:
return head
```
-### **Java**
-
```java
/**
* Definition for singly-linked list.
@@ -100,41 +98,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-/**
- * @param {ListNode} head
- * @return {ListNode}
- */
-var removeDuplicateNodes = function (head) {
- if (head == null || head.next == null) return head;
- const cache = new Set([]);
- cache.add(head.val);
- let cur = head,
- fast = head.next;
- while (fast !== null) {
- if (!cache.has(fast.val)) {
- cur.next = fast;
- cur = cur.next;
- cache.add(fast.val);
- }
- fast = fast.next;
- }
- cur.next = null;
- return head;
-};
-```
-
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -165,8 +128,6 @@ public:
};
```
-### **Go**
-
```go
func removeDuplicateNodes(head *ListNode) *ListNode {
if head == nil {
@@ -186,8 +147,6 @@ func removeDuplicateNodes(head *ListNode) *ListNode {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for singly-linked list.
@@ -219,40 +178,6 @@ function removeDuplicateNodes(head: ListNode | null): ListNode | null {
}
```
-Violence (not recommended)
-
-```ts
-/**
- * Definition for singly-linked list.
- * class ListNode {
- * val: number
- * next: ListNode | null
- * constructor(val?: number, next?: ListNode | null) {
- * this.val = (val===undefined ? 0 : val)
- * this.next = (next===undefined ? null : next)
- * }
- * }
- */
-
-function removeDuplicateNodes(head: ListNode | null): ListNode | null {
- let n1 = head;
- while (n1 != null) {
- let n2 = n1;
- while (n2.next != null) {
- if (n1.val === n2.next.val) {
- n2.next = n2.next.next;
- } else {
- n2 = n2.next;
- }
- }
- n1 = n1.next;
- }
- return head;
-}
-```
-
-### **Rust**
-
```rust
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
@@ -295,10 +220,73 @@ impl Solution {
}
```
-### **...**
-
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} head
+ * @return {ListNode}
+ */
+var removeDuplicateNodes = function (head) {
+ if (head == null || head.next == null) return head;
+ const cache = new Set([]);
+ cache.add(head.val);
+ let cur = head,
+ fast = head.next;
+ while (fast !== null) {
+ if (!cache.has(fast.val)) {
+ cur.next = fast;
+ cur = cur.next;
+ cache.add(fast.val);
+ }
+ fast = fast.next;
+ }
+ cur.next = null;
+ return head;
+};
```
+
+
+### Solution 2
+
+
+
+```ts
+/**
+ * Definition for singly-linked list.
+ * class ListNode {
+ * val: number
+ * next: ListNode | null
+ * constructor(val?: number, next?: ListNode | null) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.next = (next===undefined ? null : next)
+ * }
+ * }
+ */
+
+function removeDuplicateNodes(head: ListNode | null): ListNode | null {
+ let n1 = head;
+ while (n1 != null) {
+ let n2 = n1;
+ while (n2.next != null) {
+ if (n1.val === n2.next.val) {
+ n2.next = n2.next.next;
+ } else {
+ n2 = n2.next;
+ }
+ }
+ n1 = n1.next;
+ }
+ return head;
+}
```
+
+
diff --git a/lcci/02.02.Kth Node From End of List/README.md b/lcci/02.02.Kth Node From End of List/README.md
index b1e8711bc403d..8769f32fc9e14 100644
--- a/lcci/02.02.Kth Node From End of List/README.md
+++ b/lcci/02.02.Kth Node From End of List/README.md
@@ -20,18 +20,10 @@
## 解法
-
-
-定义 `p`、`q` 指针指向 `head`。
-
-`p` 先向前走 `k` 步,接着 `p`、`q` 同时向前走,当 `p` 指向 `null` 时,`q` 指向的节点即为链表的倒数第 `k` 个节点。
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for singly-linked list.
# class ListNode:
@@ -50,10 +42,6 @@ class Solution:
return slow.val
```
-### **Java**
-
-
-
```java
/**
* Definition for singly-linked list.
@@ -78,37 +66,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-/**
- * @param {ListNode} head
- * @param {number} k
- * @return {number}
- */
-var kthToLast = function (head, k) {
- let fast = head,
- slow = head;
- for (let i = 0; i < k; i++) {
- fast = fast.next;
- }
- while (fast != null) {
- fast = fast.next;
- slow = slow.next;
- }
- return slow.val;
-};
-```
-
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -135,8 +92,6 @@ public:
};
```
-### **Go**
-
```go
func kthToLast(head *ListNode, k int) int {
slow, fast := head, head
@@ -151,8 +106,6 @@ func kthToLast(head *ListNode, k int) int {
}
```
-### **Rust**
-
```rust
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
@@ -186,10 +139,33 @@ impl Solution {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} head
+ * @param {number} k
+ * @return {number}
+ */
+var kthToLast = function (head, k) {
+ let fast = head,
+ slow = head;
+ for (let i = 0; i < k; i++) {
+ fast = fast.next;
+ }
+ while (fast != null) {
+ fast = fast.next;
+ slow = slow.next;
+ }
+ return slow.val;
+};
```
+
+
diff --git a/lcci/02.02.Kth Node From End of List/README_EN.md b/lcci/02.02.Kth Node From End of List/README_EN.md
index 29d53bc12aa28..d9827a0fc8ddb 100644
--- a/lcci/02.02.Kth Node From End of List/README_EN.md
+++ b/lcci/02.02.Kth Node From End of List/README_EN.md
@@ -22,9 +22,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for singly-linked list.
@@ -44,8 +44,6 @@ class Solution:
return slow.val
```
-### **Java**
-
```java
/**
* Definition for singly-linked list.
@@ -70,37 +68,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-/**
- * @param {ListNode} head
- * @param {number} k
- * @return {number}
- */
-var kthToLast = function (head, k) {
- let fast = head,
- slow = head;
- for (let i = 0; i < k; i++) {
- fast = fast.next;
- }
- while (fast != null) {
- fast = fast.next;
- slow = slow.next;
- }
- return slow.val;
-};
-```
-
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -127,8 +94,6 @@ public:
};
```
-### **Go**
-
```go
func kthToLast(head *ListNode, k int) int {
slow, fast := head, head
@@ -143,8 +108,6 @@ func kthToLast(head *ListNode, k int) int {
}
```
-### **Rust**
-
```rust
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
@@ -178,10 +141,33 @@ impl Solution {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} head
+ * @param {number} k
+ * @return {number}
+ */
+var kthToLast = function (head, k) {
+ let fast = head,
+ slow = head;
+ for (let i = 0; i < k; i++) {
+ fast = fast.next;
+ }
+ while (fast != null) {
+ fast = fast.next;
+ slow = slow.next;
+ }
+ return slow.val;
+};
```
+
+
diff --git a/lcci/02.03.Delete Middle Node/README.md b/lcci/02.03.Delete Middle Node/README.md
index 0885febff27f1..68546d16ee5e0 100644
--- a/lcci/02.03.Delete Middle Node/README.md
+++ b/lcci/02.03.Delete Middle Node/README.md
@@ -25,21 +25,10 @@
## 解法
-
-
-> 此题与本站 [237. 删除链表中的节点](https://leetcode.cn/problems/delete-node-in-a-linked-list/) 题意相同。
-
-步骤:
-
-1. 将 `node` 下一个节点的值赋给 `node`。
-2. 将 `node` 的 `next` 指向 `next` 的 `next`。
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for singly-linked list.
# class ListNode:
@@ -58,10 +47,6 @@ class Solution:
node.next = node.next.next
```
-### **Java**
-
-
-
```java
/**
* Definition for singly-linked list.
@@ -79,28 +64,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-/**
- * @param {ListNode} node
- * @return {void} Do not return anything, modify node in-place instead.
- */
-var deleteNode = function (node) {
- node.val = node.next.val;
- node.next = node.next.next;
-};
-```
-
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -119,8 +82,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for singly-linked list.
@@ -135,10 +96,24 @@ func deleteNode(node *ListNode) {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} node
+ * @return {void} Do not return anything, modify node in-place instead.
+ */
+var deleteNode = function (node) {
+ node.val = node.next.val;
+ node.next = node.next.next;
+};
```
+
+
diff --git a/lcci/02.03.Delete Middle Node/README_EN.md b/lcci/02.03.Delete Middle Node/README_EN.md
index b7cfbfb2d5b0b..20406638d8395 100644
--- a/lcci/02.03.Delete Middle Node/README_EN.md
+++ b/lcci/02.03.Delete Middle Node/README_EN.md
@@ -20,9 +20,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for singly-linked list.
@@ -42,8 +42,6 @@ class Solution:
node.next = node.next.next
```
-### **Java**
-
```java
/**
* Definition for singly-linked list.
@@ -61,28 +59,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-/**
- * @param {ListNode} node
- * @return {void} Do not return anything, modify node in-place instead.
- */
-var deleteNode = function (node) {
- node.val = node.next.val;
- node.next = node.next.next;
-};
-```
-
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -101,8 +77,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for singly-linked list.
@@ -117,10 +91,24 @@ func deleteNode(node *ListNode) {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} node
+ * @return {void} Do not return anything, modify node in-place instead.
+ */
+var deleteNode = function (node) {
+ node.val = node.next.val;
+ node.next = node.next.next;
+};
```
+
+
diff --git a/lcci/02.04.Partition List/README.md b/lcci/02.04.Partition List/README.md
index 0f3cd1690282e..395f055cf2158 100644
--- a/lcci/02.04.Partition List/README.md
+++ b/lcci/02.04.Partition List/README.md
@@ -40,26 +40,12 @@
## 解法
-
-
-**方法一:拼接链表**
+### 方法一:拼接链表
创建两个链表,一个存放小于 `x` 的节点,另一个存放大于等于 `x` 的节点,之后进行拼接即可。
-**方法二:头插法**
-
-题中指出,**不需要保留节点的相对位置**。
-
-1. 遍历链表。
-2. 当节点符合小于 `x` 条件时,将其移动至头节点前方,成为新的头节点。
-3. 忽略大于等于 `x` 的节点。
-
-### **Python3**
-
-
-
```python
# Definition for singly-linked list.
# class ListNode:
@@ -85,10 +71,6 @@ class Solution:
return l1.next
```
-### **Java**
-
-
-
```java
/**
* Definition for singly-linked list.
@@ -122,8 +104,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -159,8 +139,6 @@ public:
};
```
-### **TypeScript**
-
```ts
/**
* Definition for singly-linked list.
@@ -191,10 +169,14 @@ function partition(head: ListNode | null, x: number): ListNode | null {
}
```
-### **...**
+
-```
+### 方法二:头插法
-```
+题中指出,**不需要保留节点的相对位置**。
-
+1. 遍历链表。
+2. 当节点符合小于 `x` 条件时,将其移动至头节点前方,成为新的头节点。
+3. 忽略大于等于 `x` 的节点。
+
+
diff --git a/lcci/02.04.Partition List/README_EN.md b/lcci/02.04.Partition List/README_EN.md
index d8c83733de4d9..b5d0144e8338a 100644
--- a/lcci/02.04.Partition List/README_EN.md
+++ b/lcci/02.04.Partition List/README_EN.md
@@ -18,9 +18,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for singly-linked list.
@@ -47,8 +47,6 @@ class Solution:
return l1.next
```
-### **Java**
-
```java
/**
* Definition for singly-linked list.
@@ -82,8 +80,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -119,8 +115,6 @@ public:
};
```
-### **TypeScript**
-
```ts
/**
* Definition for singly-linked list.
@@ -151,10 +145,6 @@ function partition(head: ListNode | null, x: number): ListNode | null {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/02.05.Sum Lists/README.md b/lcci/02.05.Sum Lists/README.md
index 7c59d3e478ab8..69b67acddf68b 100644
--- a/lcci/02.05.Sum Lists/README.md
+++ b/lcci/02.05.Sum Lists/README.md
@@ -29,16 +29,10 @@
## 解法
-
-
-同时遍历两链表,求节点的和与进位。
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for singly-linked list.
# class ListNode:
@@ -61,10 +55,6 @@ class Solution:
return dummy.next
```
-### **Java**
-
-
-
```java
/**
* Definition for singly-linked list.
@@ -92,8 +82,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -122,39 +110,6 @@ public:
};
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-/**
- * @param {ListNode} l1
- * @param {ListNode} l2
- * @return {ListNode}
- */
-var addTwoNumbers = function (l1, l2) {
- let carry = 0;
- const dummy = new ListNode(0);
- let cur = dummy;
- while (l1 || l2 || carry) {
- carry += (l1?.val || 0) + (l2?.val || 0);
- cur.next = new ListNode(carry % 10);
- carry = Math.floor(carry / 10);
- cur = cur.next;
- l1 = l1?.next;
- l2 = l2?.next;
- }
- return dummy.next;
-};
-```
-
-### **Go**
-
```go
/**
* Definition for singly-linked list.
@@ -184,8 +139,6 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for singly-linked list.
@@ -230,8 +183,6 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn add_two_numbers(
@@ -270,10 +221,35 @@ impl Solution {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} l1
+ * @param {ListNode} l2
+ * @return {ListNode}
+ */
+var addTwoNumbers = function (l1, l2) {
+ let carry = 0;
+ const dummy = new ListNode(0);
+ let cur = dummy;
+ while (l1 || l2 || carry) {
+ carry += (l1?.val || 0) + (l2?.val || 0);
+ cur.next = new ListNode(carry % 10);
+ carry = Math.floor(carry / 10);
+ cur = cur.next;
+ l1 = l1?.next;
+ l2 = l2?.next;
+ }
+ return dummy.next;
+};
```
+
+
diff --git a/lcci/02.05.Sum Lists/README_EN.md b/lcci/02.05.Sum Lists/README_EN.md
index 646b4051c90bc..4a2146c924bb0 100644
--- a/lcci/02.05.Sum Lists/README_EN.md
+++ b/lcci/02.05.Sum Lists/README_EN.md
@@ -32,9 +32,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for singly-linked list.
@@ -58,8 +58,6 @@ class Solution:
return dummy.next
```
-### **Java**
-
```java
/**
* Definition for singly-linked list.
@@ -87,8 +85,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -117,39 +113,6 @@ public:
};
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-/**
- * @param {ListNode} l1
- * @param {ListNode} l2
- * @return {ListNode}
- */
-var addTwoNumbers = function (l1, l2) {
- let carry = 0;
- const dummy = new ListNode(0);
- let cur = dummy;
- while (l1 || l2 || carry) {
- carry += (l1?.val || 0) + (l2?.val || 0);
- cur.next = new ListNode(carry % 10);
- carry = Math.floor(carry / 10);
- cur = cur.next;
- l1 = l1?.next;
- l2 = l2?.next;
- }
- return dummy.next;
-};
-```
-
-### **Go**
-
```go
/**
* Definition for singly-linked list.
@@ -179,8 +142,6 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for singly-linked list.
@@ -225,8 +186,6 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn add_two_numbers(
@@ -265,10 +224,35 @@ impl Solution {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} l1
+ * @param {ListNode} l2
+ * @return {ListNode}
+ */
+var addTwoNumbers = function (l1, l2) {
+ let carry = 0;
+ const dummy = new ListNode(0);
+ let cur = dummy;
+ while (l1 || l2 || carry) {
+ carry += (l1?.val || 0) + (l2?.val || 0);
+ cur.next = new ListNode(carry % 10);
+ carry = Math.floor(carry / 10);
+ cur = cur.next;
+ l1 = l1?.next;
+ l2 = l2?.next;
+ }
+ return dummy.next;
+};
```
+
+
diff --git a/lcci/02.06.Palindrome Linked List/README.md b/lcci/02.06.Palindrome Linked List/README.md
index bb8655e8f569e..9abc0cd6a8e25 100644
--- a/lcci/02.06.Palindrome Linked List/README.md
+++ b/lcci/02.06.Palindrome Linked List/README.md
@@ -28,16 +28,10 @@
## 解法
-
-
-先用快慢指针找到链表的中点,接着反转右半部分的链表。然后同时遍历前后两段链表,若前后两段链表节点对应的值不等,说明不是回文链表,否则说明是回文链表。
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for singly-linked list.
# class ListNode:
@@ -63,10 +57,6 @@ class Solution:
return True
```
-### **Java**
-
-
-
```java
/**
* Definition for singly-linked list.
@@ -110,7 +100,90 @@ class Solution {
}
```
-### **JavaScript**
+```go
+func isPalindrome(head *ListNode) bool {
+ if head == nil {
+ return true
+ }
+ m := mid(head)
+ temp := reverse(m.Next)
+ m.Next = nil
+ p, q := head, temp
+ res := true
+ for p != nil && q != nil {
+ if p.Val != q.Val {
+ res = false
+ break
+ }
+ p = p.Next
+ q = q.Next
+ }
+ m.Next = reverse(temp)
+ return res
+}
+
+func mid(head *ListNode) *ListNode {
+ slow, fast := head, head.Next
+ for fast != nil && fast.Next != nil {
+ slow = slow.Next
+ fast = fast.Next.Next
+ }
+ return slow
+}
+
+func reverse(head *ListNode) *ListNode {
+ var prev *ListNode = nil
+ for head != nil {
+ temp := head.Next
+ head.Next = prev
+ prev = head
+ head = temp
+ }
+ return prev
+}
+```
+
+```ts
+/**
+ * Definition for singly-linked list.
+ * class ListNode {
+ * val: number
+ * next: ListNode | null
+ * constructor(val?: number, next?: ListNode | null) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.next = (next===undefined ? null : next)
+ * }
+ * }
+ */
+
+function isPalindrome(head: ListNode | null): boolean {
+ if (head == null || head.next == null) return true;
+ // 快慢指针定位到中点
+ let slow: ListNode = head,
+ fast: ListNode = head.next;
+ while (fast != null && fast.next != null) {
+ slow = slow.next;
+ fast = fast.next.next;
+ }
+ // 翻转链表
+ let cur: ListNode = slow.next;
+ slow.next = null;
+ let prev: ListNode = null;
+ while (cur != null) {
+ let t: ListNode = cur.next;
+ cur.next = prev;
+ prev = cur;
+ cur = t;
+ }
+ // 判断回文
+ while (prev != null) {
+ if (prev.val != head.val) return false;
+ prev = prev.next;
+ head = head.next;
+ }
+ return true;
+}
+```
```js
/**
@@ -154,8 +227,6 @@ var isPalindrome = function (head) {
};
```
-### **C#**
-
```cs
/**
* Definition for singly-linked list.
@@ -205,49 +276,11 @@ public class Solution {
}
```
-### **TypeScript**
+
-```ts
-/**
- * Definition for singly-linked list.
- * class ListNode {
- * val: number
- * next: ListNode | null
- * constructor(val?: number, next?: ListNode | null) {
- * this.val = (val===undefined ? 0 : val)
- * this.next = (next===undefined ? null : next)
- * }
- * }
- */
+### 方法二
-function isPalindrome(head: ListNode | null): boolean {
- if (head == null || head.next == null) return true;
- // 快慢指针定位到中点
- let slow: ListNode = head,
- fast: ListNode = head.next;
- while (fast != null && fast.next != null) {
- slow = slow.next;
- fast = fast.next.next;
- }
- // 翻转链表
- let cur: ListNode = slow.next;
- slow.next = null;
- let prev: ListNode = null;
- while (cur != null) {
- let t: ListNode = cur.next;
- cur.next = prev;
- prev = cur;
- cur = t;
- }
- // 判断回文
- while (prev != null) {
- if (prev.val != head.val) return false;
- prev = prev.next;
- head = head.next;
- }
- return true;
-}
-```
+
```ts
/**
@@ -278,55 +311,6 @@ function isPalindrome(head: ListNode | null): boolean {
}
```
-### **Go**
-
-```go
-func isPalindrome(head *ListNode) bool {
- if head == nil {
- return true
- }
- m := mid(head)
- temp := reverse(m.Next)
- m.Next = nil
- p, q := head, temp
- res := true
- for p != nil && q != nil {
- if p.Val != q.Val {
- res = false
- break
- }
- p = p.Next
- q = q.Next
- }
- m.Next = reverse(temp)
- return res
-}
-
-func mid(head *ListNode) *ListNode {
- slow, fast := head, head.Next
- for fast != nil && fast.Next != nil {
- slow = slow.Next
- fast = fast.Next.Next
- }
- return slow
-}
-
-func reverse(head *ListNode) *ListNode {
- var prev *ListNode = nil
- for head != nil {
- temp := head.Next
- head.Next = prev
- prev = head
- head = temp
- }
- return prev
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/02.06.Palindrome Linked List/README_EN.md b/lcci/02.06.Palindrome Linked List/README_EN.md
index 72eae5adec88e..3bf8f86c4af95 100644
--- a/lcci/02.06.Palindrome Linked List/README_EN.md
+++ b/lcci/02.06.Palindrome Linked List/README_EN.md
@@ -36,9 +36,9 @@ Could you do it in O(n) time and O(1) space?
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for singly-linked list.
@@ -65,8 +65,6 @@ class Solution:
return True
```
-### **Java**
-
```java
/**
* Definition for singly-linked list.
@@ -110,7 +108,90 @@ class Solution {
}
```
-### **JavaScript**
+```go
+func isPalindrome(head *ListNode) bool {
+ if head == nil {
+ return true
+ }
+ m := mid(head)
+ temp := reverse(m.Next)
+ m.Next = nil
+ p, q := head, temp
+ res := true
+ for p != nil && q != nil {
+ if p.Val != q.Val {
+ res = false
+ break
+ }
+ p = p.Next
+ q = q.Next
+ }
+ m.Next = reverse(temp)
+ return res
+}
+
+func mid(head *ListNode) *ListNode {
+ slow, fast := head, head.Next
+ for fast != nil && fast.Next != nil {
+ slow = slow.Next
+ fast = fast.Next.Next
+ }
+ return slow
+}
+
+func reverse(head *ListNode) *ListNode {
+ var prev *ListNode = nil
+ for head != nil {
+ temp := head.Next
+ head.Next = prev
+ prev = head
+ head = temp
+ }
+ return prev
+}
+```
+
+```ts
+/**
+ * Definition for singly-linked list.
+ * class ListNode {
+ * val: number
+ * next: ListNode | null
+ * constructor(val?: number, next?: ListNode | null) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.next = (next===undefined ? null : next)
+ * }
+ * }
+ */
+
+function isPalindrome(head: ListNode | null): boolean {
+ if (head == null || head.next == null) return true;
+ // 快慢指针定位到中点
+ let slow: ListNode = head,
+ fast: ListNode = head.next;
+ while (fast != null && fast.next != null) {
+ slow = slow.next;
+ fast = fast.next.next;
+ }
+ // 翻转链表
+ let cur: ListNode = slow.next;
+ slow.next = null;
+ let prev: ListNode = null;
+ while (cur != null) {
+ let t: ListNode = cur.next;
+ cur.next = prev;
+ prev = cur;
+ cur = t;
+ }
+ // 判断回文
+ while (prev != null) {
+ if (prev.val != head.val) return false;
+ prev = prev.next;
+ head = head.next;
+ }
+ return true;
+}
+```
```js
/**
@@ -154,8 +235,6 @@ var isPalindrome = function (head) {
};
```
-### **C#**
-
```cs
/**
* Definition for singly-linked list.
@@ -205,49 +284,11 @@ public class Solution {
}
```
-### **TypeScript**
+
-```ts
-/**
- * Definition for singly-linked list.
- * class ListNode {
- * val: number
- * next: ListNode | null
- * constructor(val?: number, next?: ListNode | null) {
- * this.val = (val===undefined ? 0 : val)
- * this.next = (next===undefined ? null : next)
- * }
- * }
- */
+### Solution 2
-function isPalindrome(head: ListNode | null): boolean {
- if (head == null || head.next == null) return true;
- // 快慢指针定位到中点
- let slow: ListNode = head,
- fast: ListNode = head.next;
- while (fast != null && fast.next != null) {
- slow = slow.next;
- fast = fast.next.next;
- }
- // 翻转链表
- let cur: ListNode = slow.next;
- slow.next = null;
- let prev: ListNode = null;
- while (cur != null) {
- let t: ListNode = cur.next;
- cur.next = prev;
- prev = cur;
- cur = t;
- }
- // 判断回文
- while (prev != null) {
- if (prev.val != head.val) return false;
- prev = prev.next;
- head = head.next;
- }
- return true;
-}
-```
+
```ts
/**
@@ -278,55 +319,6 @@ function isPalindrome(head: ListNode | null): boolean {
}
```
-### **Go**
-
-```go
-func isPalindrome(head *ListNode) bool {
- if head == nil {
- return true
- }
- m := mid(head)
- temp := reverse(m.Next)
- m.Next = nil
- p, q := head, temp
- res := true
- for p != nil && q != nil {
- if p.Val != q.Val {
- res = false
- break
- }
- p = p.Next
- q = q.Next
- }
- m.Next = reverse(temp)
- return res
-}
-
-func mid(head *ListNode) *ListNode {
- slow, fast := head, head.Next
- for fast != nil && fast.Next != nil {
- slow = slow.Next
- fast = fast.Next.Next
- }
- return slow
-}
-
-func reverse(head *ListNode) *ListNode {
- var prev *ListNode = nil
- for head != nil {
- temp := head.Next
- head.Next = prev
- prev = head
- head = temp
- }
- return prev
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/02.07.Intersection of Two Linked Lists/README.md b/lcci/02.07.Intersection of Two Linked Lists/README.md
index a54212d0bb0d3..fc268de03e30a 100644
--- a/lcci/02.07.Intersection of Two Linked Lists/README.md
+++ b/lcci/02.07.Intersection of Two Linked Lists/README.md
@@ -9,20 +9,10 @@
## 解法
-
-
-使用两个指针 `cur1`, `cur2` 分别指向两个链表 `headA`, `headB`。
-
-同时遍历链表,当 `cur1` 到达链表 `headA` 的末尾时,重新定位到链表 `headB` 的头节点;当 `cur2` 到达链表 `headB` 的末尾时,重新定位到链表 `headA` 的头节点。
-
-若两指针相遇,所指向的结点就是第一个公共节点。若没相遇,说明两链表无公共节点,此时两个指针都指向 `null`。
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for singly-linked list.
# class ListNode:
@@ -40,10 +30,6 @@ class Solution:
return cur1
```
-### **Java**
-
-
-
```java
/**
* Definition for singly-linked list.
@@ -68,8 +54,6 @@ public class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -93,35 +77,6 @@ public:
};
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-
-/**
- * @param {ListNode} headA
- * @param {ListNode} headB
- * @return {ListNode}
- */
-var getIntersectionNode = function (headA, headB) {
- let cur1 = headA;
- let cur2 = headB;
- while (cur1 != cur2) {
- cur1 = cur1 ? cur1.next : headB;
- cur2 = cur2 ? cur2.next : headA;
- }
- return cur1;
-};
-```
-
-### **Go**
-
```go
/**
* Definition for singly-linked list.
@@ -148,10 +103,31 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode {
}
```
-### **...**
-
-```
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} headA
+ * @param {ListNode} headB
+ * @return {ListNode}
+ */
+var getIntersectionNode = function (headA, headB) {
+ let cur1 = headA;
+ let cur2 = headB;
+ while (cur1 != cur2) {
+ cur1 = cur1 ? cur1.next : headB;
+ cur2 = cur2 ? cur2.next : headA;
+ }
+ return cur1;
+};
```
+
+
diff --git a/lcci/02.07.Intersection of Two Linked Lists/README_EN.md b/lcci/02.07.Intersection of Two Linked Lists/README_EN.md
index 8674d3651b32f..bd2ee8ba86223 100644
--- a/lcci/02.07.Intersection of Two Linked Lists/README_EN.md
+++ b/lcci/02.07.Intersection of Two Linked Lists/README_EN.md
@@ -47,9 +47,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for singly-linked list.
@@ -68,8 +68,6 @@ class Solution:
return cur1
```
-### **Java**
-
```java
/**
* Definition for singly-linked list.
@@ -94,8 +92,6 @@ public class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -119,35 +115,6 @@ public:
};
```
-### **JavaScript**
-
-```js
-/**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
-
-/**
- * @param {ListNode} headA
- * @param {ListNode} headB
- * @return {ListNode}
- */
-var getIntersectionNode = function (headA, headB) {
- let cur1 = headA;
- let cur2 = headB;
- while (cur1 != cur2) {
- cur1 = cur1 ? cur1.next : headB;
- cur2 = cur2 ? cur2.next : headA;
- }
- return cur1;
-};
-```
-
-### **Go**
-
```go
/**
* Definition for singly-linked list.
@@ -174,10 +141,31 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode {
}
```
-### **...**
-
-```
+```js
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ * this.val = val;
+ * this.next = null;
+ * }
+ */
+/**
+ * @param {ListNode} headA
+ * @param {ListNode} headB
+ * @return {ListNode}
+ */
+var getIntersectionNode = function (headA, headB) {
+ let cur1 = headA;
+ let cur2 = headB;
+ while (cur1 != cur2) {
+ cur1 = cur1 ? cur1.next : headB;
+ cur2 = cur2 ? cur2.next : headA;
+ }
+ return cur1;
+};
```
+
+
diff --git a/lcci/02.08.Linked List Cycle/README.md b/lcci/02.08.Linked List Cycle/README.md
index 3bb387564651d..799505b036f3e 100644
--- a/lcci/02.08.Linked List Cycle/README.md
+++ b/lcci/02.08.Linked List Cycle/README.md
@@ -9,28 +9,10 @@
## 解法
-
-
-先利用快慢指针判断链表是否有环,没有环则直接返回 `null`。
-
-若链表有环,我们分析快慢相遇时走过的距离。
-
-对于慢指针(每次走 1 步),走过的距离为 `S=X+Y` ①;快指针(每次走 2 步)走过的距离为 `2S=X+Y+N(Y+Z)` ②。如下图所示,其中 `N` 表示快指针与慢指针相遇时在环中所走过的圈数,而我们要求的环入口,也即是 `X` 的距离:
-
-
-
-我们根据式子 ①②,得出 `X+Y=N(Y+Z)` => `X=(N-1)(Y+Z)+Z`。
-
-当 `N=1`(快指针在环中走了一圈与慢指针相遇) 时,`X=(1-1)(Y+Z)+Z`,即 `X=Z`。此时只要定义一个 `p` 指针指向头节点,然后慢指针与 `p` 开始同时走,当慢指针与 `p` 相遇时,也就到达了环入口,直接返回 `p` 即可。
-
-当 `N>1`时,也是同样的,说明慢指针除了走 `Z` 步,还需要绕 `N-1` 圈才能与 `p` 相遇。
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for singly-linked list.
# class ListNode:
@@ -54,10 +36,6 @@ class Solution:
return p
```
-### **Java**
-
-
-
```java
/**
* Definition for singly-linked list.
@@ -92,8 +70,6 @@ public class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -127,7 +103,31 @@ public:
};
```
-### **JavaScript**
+```go
+/**
+ * Definition for singly-linked list.
+ * type ListNode struct {
+ * Val int
+ * Next *ListNode
+ * }
+ */
+func detectCycle(head *ListNode) *ListNode {
+ slow, fast := head, head
+ hasCycle := false
+ for !hasCycle && fast != nil && fast.Next != nil {
+ slow, fast = slow.Next, fast.Next.Next
+ hasCycle = slow == fast
+ }
+ if !hasCycle {
+ return nil
+ }
+ p := head
+ for p != slow {
+ p, slow = p.Next, slow.Next
+ }
+ return p
+}
+```
```js
/**
@@ -163,38 +163,6 @@ var detectCycle = function (head) {
};
```
-### **Go**
-
-```go
-/**
- * Definition for singly-linked list.
- * type ListNode struct {
- * Val int
- * Next *ListNode
- * }
- */
-func detectCycle(head *ListNode) *ListNode {
- slow, fast := head, head
- hasCycle := false
- for !hasCycle && fast != nil && fast.Next != nil {
- slow, fast = slow.Next, fast.Next.Next
- hasCycle = slow == fast
- }
- if !hasCycle {
- return nil
- }
- p := head
- for p != slow {
- p, slow = p.Next, slow.Next
- }
- return p
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/02.08.Linked List Cycle/README_EN.md b/lcci/02.08.Linked List Cycle/README_EN.md
index 31601d86a37ff..b2d71ab97c1dd 100644
--- a/lcci/02.08.Linked List Cycle/README_EN.md
+++ b/lcci/02.08.Linked List Cycle/README_EN.md
@@ -38,9 +38,9 @@ Can you solve it without using additional space?
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for singly-linked list.
@@ -65,8 +65,6 @@ class Solution:
return p
```
-### **Java**
-
```java
/**
* Definition for singly-linked list.
@@ -101,8 +99,6 @@ public class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for singly-linked list.
@@ -136,7 +132,31 @@ public:
};
```
-### **JavaScript**
+```go
+/**
+ * Definition for singly-linked list.
+ * type ListNode struct {
+ * Val int
+ * Next *ListNode
+ * }
+ */
+func detectCycle(head *ListNode) *ListNode {
+ slow, fast := head, head
+ hasCycle := false
+ for !hasCycle && fast != nil && fast.Next != nil {
+ slow, fast = slow.Next, fast.Next.Next
+ hasCycle = slow == fast
+ }
+ if !hasCycle {
+ return nil
+ }
+ p := head
+ for p != slow {
+ p, slow = p.Next, slow.Next
+ }
+ return p
+}
+```
```js
/**
@@ -172,38 +192,6 @@ var detectCycle = function (head) {
};
```
-### **Go**
-
-```go
-/**
- * Definition for singly-linked list.
- * type ListNode struct {
- * Val int
- * Next *ListNode
- * }
- */
-func detectCycle(head *ListNode) *ListNode {
- slow, fast := head, head
- hasCycle := false
- for !hasCycle && fast != nil && fast.Next != nil {
- slow, fast = slow.Next, fast.Next.Next
- hasCycle = slow == fast
- }
- if !hasCycle {
- return nil
- }
- p := head
- for p != slow {
- p, slow = p.Next, slow.Next
- }
- return p
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.01.Three in One/README.md b/lcci/03.01.Three in One/README.md
index 6092afc18bb55..32a5e66fbc233 100644
--- a/lcci/03.01.Three in One/README.md
+++ b/lcci/03.01.Three in One/README.md
@@ -32,16 +32,10 @@
## 解法
-
-
-二维数组解决;也可以使用一维数组,以下标 `0,3,6,..`、`1,4,7,..`、`2,5,8,..` 区分,一维数组最后三个元素记录每个栈的元素个数。
+### 方法一
-### **Python3**
-
-
-
```python
class TripleInOne:
def __init__(self, stackSize: int):
@@ -70,10 +64,6 @@ class TripleInOne:
# param_4 = obj.isEmpty(stackNum)
```
-### **Java**
-
-
-
```java
class TripleInOne {
private int[] s;
@@ -118,8 +108,6 @@ class TripleInOne {
*/
```
-### **Go**
-
```go
type TripleInOne struct {
data []int
@@ -180,10 +168,6 @@ func (this *TripleInOne) IsEmpty(stackNum int) bool {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.01.Three in One/README_EN.md b/lcci/03.01.Three in One/README_EN.md
index 47bd407159d9c..ec7d209a4dbab 100644
--- a/lcci/03.01.Three in One/README_EN.md
+++ b/lcci/03.01.Three in One/README_EN.md
@@ -46,9 +46,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class TripleInOne:
@@ -78,8 +78,6 @@ class TripleInOne:
# param_4 = obj.isEmpty(stackNum)
```
-### **Java**
-
```java
class TripleInOne {
private int[] s;
@@ -124,8 +122,6 @@ class TripleInOne {
*/
```
-### **Go**
-
```go
type TripleInOne struct {
data []int
@@ -186,10 +182,6 @@ func (this *TripleInOne) IsEmpty(stackNum int) bool {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.02.Min Stack/README.md b/lcci/03.02.Min Stack/README.md
index 36f7dee4a37b1..5222d092fd2a6 100644
--- a/lcci/03.02.Min Stack/README.md
+++ b/lcci/03.02.Min Stack/README.md
@@ -9,9 +9,7 @@
## 解法
-
-
-**方法一:双栈**
+### 方法一:双栈
我们用两个栈来实现,其中`stk1` 用来存储数据,`stk2` 用来存储当前栈中的最小值。初始时,`stk2` 中存储一个极大值。
@@ -24,10 +22,6 @@
-### **Python3**
-
-
-
```python
class MinStack:
def __init__(self):
@@ -60,10 +54,6 @@ class MinStack:
# param_4 = obj.getMin()
```
-### **Java**
-
-
-
```java
class MinStack {
private Deque stk1 = new ArrayDeque<>();
@@ -103,8 +93,6 @@ class MinStack {
*/
```
-### **C++**
-
```cpp
class MinStack {
public:
@@ -146,48 +134,6 @@ private:
*/
```
-### **TypeScript**
-
-```ts
-class MinStack {
- stack: number[];
- mins: number[];
- constructor() {
- this.stack = [];
- this.mins = [];
- }
-
- push(x: number): void {
- this.stack.push(x);
- this.mins.push(Math.min(this.getMin(), x));
- }
-
- pop(): void {
- this.stack.pop();
- this.mins.pop();
- }
-
- top(): number {
- return this.stack[this.stack.length - 1];
- }
-
- getMin(): number {
- return this.mins.length == 0 ? Infinity : this.mins[this.mins.length - 1];
- }
-}
-
-/**
- * Your MinStack object will be instantiated and called as such:
- * var obj = new MinStack()
- * obj.push(x)
- * obj.pop()
- * var param_3 = obj.top()
- * var param_4 = obj.getMin()
- */
-```
-
-### **Go**
-
```go
type MinStack struct {
stk1 []int
@@ -227,7 +173,43 @@ func (this *MinStack) GetMin() int {
*/
```
-### **Rust**
+```ts
+class MinStack {
+ stack: number[];
+ mins: number[];
+ constructor() {
+ this.stack = [];
+ this.mins = [];
+ }
+
+ push(x: number): void {
+ this.stack.push(x);
+ this.mins.push(Math.min(this.getMin(), x));
+ }
+
+ pop(): void {
+ this.stack.pop();
+ this.mins.pop();
+ }
+
+ top(): number {
+ return this.stack[this.stack.length - 1];
+ }
+
+ getMin(): number {
+ return this.mins.length == 0 ? Infinity : this.mins[this.mins.length - 1];
+ }
+}
+
+/**
+ * Your MinStack object will be instantiated and called as such:
+ * var obj = new MinStack()
+ * obj.push(x)
+ * obj.pop()
+ * var param_3 = obj.top()
+ * var param_4 = obj.getMin()
+ */
+```
```rust
use std::collections::VecDeque;
@@ -277,8 +259,6 @@ impl MinStack {
*/
```
-### **C#**
-
```cs
public class MinStack {
private Stack stk1 = new Stack();
@@ -318,10 +298,6 @@ public class MinStack {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.02.Min Stack/README_EN.md b/lcci/03.02.Min Stack/README_EN.md
index 6c5dbfd9dd068..dfa3b78c33932 100644
--- a/lcci/03.02.Min Stack/README_EN.md
+++ b/lcci/03.02.Min Stack/README_EN.md
@@ -28,41 +28,42 @@ minStack.getMin(); --> return -2.
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class MinStack:
def __init__(self):
- self.stk1 = []
- self.stk2 = [inf]
+ """
+ initialize your data structure here.
+ """
+ self.s = []
+ self.mins = [inf]
- def push(self, x: int) -> None:
- self.stk1.append(x)
- self.stk2.append(min(x, self.stk2[-1]))
+ def push(self, val: int) -> None:
+ self.s.append(val)
+ self.mins.append(min(self.mins[-1], val))
def pop(self) -> None:
- self.stk1.pop()
- self.stk2.pop()
+ self.s.pop()
+ self.mins.pop()
def top(self) -> int:
- return self.stk1[-1]
+ return self.s[-1]
def getMin(self) -> int:
- return self.stk2[-1]
+ return self.mins[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
-# obj.push(x)
+# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
```
-### **Java**
-
```java
class MinStack {
private Deque stk1 = new ArrayDeque<>();
@@ -102,8 +103,6 @@ class MinStack {
*/
```
-### **C++**
-
```cpp
class MinStack {
public:
@@ -145,8 +144,6 @@ private:
*/
```
-### **Go**
-
```go
type MinStack struct {
stk1 []int
@@ -186,34 +183,31 @@ func (this *MinStack) GetMin() int {
*/
```
-### **TypeScript**
-
```ts
class MinStack {
- stk1: number[];
- stk2: number[];
-
+ stack: number[];
+ mins: number[];
constructor() {
- this.stk1 = [];
- this.stk2 = [Infinity];
+ this.stack = [];
+ this.mins = [];
}
push(x: number): void {
- this.stk1.push(x);
- this.stk2.push(Math.min(x, this.stk2[this.stk2.length - 1]));
+ this.stack.push(x);
+ this.mins.push(Math.min(this.getMin(), x));
}
pop(): void {
- this.stk1.pop();
- this.stk2.pop();
+ this.stack.pop();
+ this.mins.pop();
}
top(): number {
- return this.stk1[this.stk1.length - 1];
+ return this.stack[this.stack.length - 1];
}
getMin(): number {
- return this.stk2[this.stk2.length - 1];
+ return this.mins.length == 0 ? Infinity : this.mins[this.mins.length - 1];
}
}
@@ -227,8 +221,6 @@ class MinStack {
*/
```
-### **Rust**
-
```rust
use std::collections::VecDeque;
struct MinStack {
@@ -277,8 +269,6 @@ impl MinStack {
*/
```
-### **C#**
-
```cs
public class MinStack {
private Stack stk1 = new Stack();
@@ -318,10 +308,6 @@ public class MinStack {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.03.Stack of Plates/README.md b/lcci/03.03.Stack of Plates/README.md
index 76a14d5542480..f51a85641164d 100644
--- a/lcci/03.03.Stack of Plates/README.md
+++ b/lcci/03.03.Stack of Plates/README.md
@@ -24,18 +24,12 @@
## 解法
-
-
-**方法一:模拟**
+### 方法一:模拟
用列表模拟栈的集合,每个栈的容量为 `cap`,当栈满时,新建一个栈。
-### **Python3**
-
-
-
```python
class StackOfPlates:
def __init__(self, cap: int):
@@ -68,10 +62,6 @@ class StackOfPlates:
# param_3 = obj.popAt(index)
```
-### **Java**
-
-
-
```java
class StackOfPlates {
private List> stk = new ArrayList<>();
@@ -116,8 +106,6 @@ class StackOfPlates {
*/
```
-### **C++**
-
```cpp
class StackOfPlates {
public:
@@ -161,8 +149,6 @@ private:
*/
```
-### **Go**
-
```go
type StackOfPlates struct {
stk [][]int
@@ -209,8 +195,6 @@ func (this *StackOfPlates) PopAt(index int) int {
*/
```
-### **TypeScript**
-
```ts
class StackOfPlates {
private cap: number;
@@ -264,10 +248,6 @@ class StackOfPlates {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.03.Stack of Plates/README_EN.md b/lcci/03.03.Stack of Plates/README_EN.md
index a2a9f06f28cec..55c1ba2995069 100644
--- a/lcci/03.03.Stack of Plates/README_EN.md
+++ b/lcci/03.03.Stack of Plates/README_EN.md
@@ -39,9 +39,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class StackOfPlates:
@@ -75,8 +75,6 @@ class StackOfPlates:
# param_3 = obj.popAt(index)
```
-### **Java**
-
```java
class StackOfPlates {
private List> stk = new ArrayList<>();
@@ -121,8 +119,6 @@ class StackOfPlates {
*/
```
-### **C++**
-
```cpp
class StackOfPlates {
public:
@@ -166,8 +162,6 @@ private:
*/
```
-### **Go**
-
```go
type StackOfPlates struct {
stk [][]int
@@ -214,8 +208,6 @@ func (this *StackOfPlates) PopAt(index int) int {
*/
```
-### **TypeScript**
-
```ts
class StackOfPlates {
private cap: number;
@@ -269,10 +261,6 @@ class StackOfPlates {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.04.Implement Queue using Stacks/README.md b/lcci/03.04.Implement Queue using Stacks/README.md
index bbd5adb112380..18f76c3c9be14 100644
--- a/lcci/03.04.Implement Queue using Stacks/README.md
+++ b/lcci/03.04.Implement Queue using Stacks/README.md
@@ -9,18 +9,10 @@
## 解法
-
-
-- 每次压入元素时,放入第 1 个栈中;
-- 第 2 个栈不为空时,不能倒入元素;
-- 第 2 个栈为空时,必须将第 1 个栈的所有元素按顺序倒入第 2 个栈中。
+### 方法一
-### **Python3**
-
-
-
```python
class MyQueue:
def __init__(self):
@@ -68,10 +60,6 @@ class MyQueue:
# param_4 = obj.empty()
```
-### **Java**
-
-
-
```java
class MyQueue {
private Stack s1;
@@ -124,8 +112,6 @@ class MyQueue {
*/
```
-### **Go**
-
```go
type MyQueue struct {
s1, s2 []int
@@ -184,8 +170,6 @@ func (this *MyQueue) transfer() {
*/
```
-### **TypeScript**
-
```ts
class MyQueue {
private inStack: number[];
@@ -235,10 +219,6 @@ class MyQueue {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.04.Implement Queue using Stacks/README_EN.md b/lcci/03.04.Implement Queue using Stacks/README_EN.md
index 79b001ffc36f0..e06cc67a9f111 100644
--- a/lcci/03.04.Implement Queue using Stacks/README_EN.md
+++ b/lcci/03.04.Implement Queue using Stacks/README_EN.md
@@ -40,9 +40,9 @@ queue.empty(); // return false
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class MyQueue:
@@ -91,8 +91,6 @@ class MyQueue:
# param_4 = obj.empty()
```
-### **Java**
-
```java
class MyQueue {
private Stack s1;
@@ -145,8 +143,6 @@ class MyQueue {
*/
```
-### **Go**
-
```go
type MyQueue struct {
s1, s2 []int
@@ -205,8 +201,6 @@ func (this *MyQueue) transfer() {
*/
```
-### **TypeScript**
-
```ts
class MyQueue {
private inStack: number[];
@@ -256,10 +250,6 @@ class MyQueue {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.05.Sort of Stacks/README.md b/lcci/03.05.Sort of Stacks/README.md
index 2fcecc00f8242..7237b9d2c44ad 100644
--- a/lcci/03.05.Sort of Stacks/README.md
+++ b/lcci/03.05.Sort of Stacks/README.md
@@ -33,16 +33,10 @@
## 解法
-
-
-利用辅助栈实现 `push` 操作,其余操作不变。
+### 方法一
-### **Python3**
-
-
-
```python
class SortedStack:
def __init__(self):
@@ -67,10 +61,6 @@ class SortedStack:
return len(self.s) == 0
```
-### **Java**
-
-
-
```java
class SortedStack {
private Stack s;
@@ -114,7 +104,45 @@ class SortedStack {
*/
```
-### **TypeScript**
+```go
+type SortedStack struct {
+ data []int
+}
+
+func Constructor() SortedStack {
+ return SortedStack{make([]int, 0)}
+}
+
+func (s *SortedStack) Push(val int) {
+ temp := make([]int, 0)
+ for !s.IsEmpty() && s.Peek() < val {
+ temp = append(temp, s.Peek())
+ s.Pop()
+ }
+ s.data = append(s.data, val)
+ for len(temp) > 0 {
+ s.data = append(s.data, temp[len(temp)-1])
+ temp = temp[:len(temp)-1]
+ }
+}
+
+func (s *SortedStack) Pop() {
+ if !s.IsEmpty() {
+ s.data = s.data[:len(s.data)-1]
+ }
+}
+
+func (s *SortedStack) Peek() int {
+ if !s.IsEmpty() {
+ return s.data[len(s.data)-1]
+ }
+ return -1
+}
+
+func (s *SortedStack) IsEmpty() bool {
+ return len(s.data) == 0
+}
+```
```ts
class SortedStack {
@@ -157,92 +185,6 @@ class SortedStack {
*/
```
-```ts
-class SortedStack {
- private stack: number[];
-
- constructor() {
- this.stack = [];
- }
-
- push(val: number): void {
- if (this.isEmpty() || this.peek() > val) {
- this.stack.push(val);
- return;
- }
-
- const tmp = this.stack.pop();
- this.push(val);
- this.stack.push(tmp);
- }
-
- pop(): void {
- this.stack.pop();
- }
-
- peek(): number {
- return this.stack[this.stack.length - 1] ?? -1;
- }
-
- isEmpty(): boolean {
- return this.stack.length === 0;
- }
-}
-
-/**
- * Your SortedStack object will be instantiated and called as such:
- * var obj = new SortedStack()
- * obj.push(val)
- * obj.pop()
- * var param_3 = obj.peek()
- * var param_4 = obj.isEmpty()
- */
-```
-
-### **Go**
-
-```go
-type SortedStack struct {
- data []int
-}
-
-func Constructor() SortedStack {
- return SortedStack{make([]int, 0)}
-}
-
-func (s *SortedStack) Push(val int) {
- temp := make([]int, 0)
- for !s.IsEmpty() && s.Peek() < val {
- temp = append(temp, s.Peek())
- s.Pop()
- }
- s.data = append(s.data, val)
- for len(temp) > 0 {
- s.data = append(s.data, temp[len(temp)-1])
- temp = temp[:len(temp)-1]
- }
-}
-
-func (s *SortedStack) Pop() {
- if !s.IsEmpty() {
- s.data = s.data[:len(s.data)-1]
- }
-}
-
-func (s *SortedStack) Peek() int {
- if !s.IsEmpty() {
- return s.data[len(s.data)-1]
- }
- return -1
-}
-
-func (s *SortedStack) IsEmpty() bool {
- return len(s.data) == 0
-}
-```
-
-### **Rust**
-
```rust
use std::collections::VecDeque;
struct SortedStack {
@@ -289,10 +231,54 @@ impl SortedStack {
*/
```
-### **...**
+
-```
+### 方法二
+
+
+```ts
+class SortedStack {
+ private stack: number[];
+
+ constructor() {
+ this.stack = [];
+ }
+
+ push(val: number): void {
+ if (this.isEmpty() || this.peek() > val) {
+ this.stack.push(val);
+ return;
+ }
+
+ const tmp = this.stack.pop();
+ this.push(val);
+ this.stack.push(tmp);
+ }
+
+ pop(): void {
+ this.stack.pop();
+ }
+
+ peek(): number {
+ return this.stack[this.stack.length - 1] ?? -1;
+ }
+
+ isEmpty(): boolean {
+ return this.stack.length === 0;
+ }
+}
+
+/**
+ * Your SortedStack object will be instantiated and called as such:
+ * var obj = new SortedStack()
+ * obj.push(val)
+ * obj.pop()
+ * var param_3 = obj.peek()
+ * var param_4 = obj.isEmpty()
+ */
```
+
+
diff --git a/lcci/03.05.Sort of Stacks/README_EN.md b/lcci/03.05.Sort of Stacks/README_EN.md
index 560fede6bb67b..067fe202e020d 100644
--- a/lcci/03.05.Sort of Stacks/README_EN.md
+++ b/lcci/03.05.Sort of Stacks/README_EN.md
@@ -46,9 +46,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class SortedStack:
@@ -74,8 +74,6 @@ class SortedStack:
return len(self.s) == 0
```
-### **Java**
-
```java
class SortedStack {
private Stack s;
@@ -119,7 +117,45 @@ class SortedStack {
*/
```
-### **TypeScript**
+```go
+type SortedStack struct {
+ data []int
+}
+
+func Constructor() SortedStack {
+ return SortedStack{make([]int, 0)}
+}
+
+func (s *SortedStack) Push(val int) {
+ temp := make([]int, 0)
+ for !s.IsEmpty() && s.Peek() < val {
+ temp = append(temp, s.Peek())
+ s.Pop()
+ }
+ s.data = append(s.data, val)
+ for len(temp) > 0 {
+ s.data = append(s.data, temp[len(temp)-1])
+ temp = temp[:len(temp)-1]
+ }
+}
+
+func (s *SortedStack) Pop() {
+ if !s.IsEmpty() {
+ s.data = s.data[:len(s.data)-1]
+ }
+}
+
+func (s *SortedStack) Peek() int {
+ if !s.IsEmpty() {
+ return s.data[len(s.data)-1]
+ }
+ return -1
+}
+
+func (s *SortedStack) IsEmpty() bool {
+ return len(s.data) == 0
+}
+```
```ts
class SortedStack {
@@ -162,92 +198,6 @@ class SortedStack {
*/
```
-```ts
-class SortedStack {
- private stack: number[];
-
- constructor() {
- this.stack = [];
- }
-
- push(val: number): void {
- if (this.isEmpty() || this.peek() > val) {
- this.stack.push(val);
- return;
- }
-
- const tmp = this.stack.pop();
- this.push(val);
- this.stack.push(tmp);
- }
-
- pop(): void {
- this.stack.pop();
- }
-
- peek(): number {
- return this.stack[this.stack.length - 1] ?? -1;
- }
-
- isEmpty(): boolean {
- return this.stack.length === 0;
- }
-}
-
-/**
- * Your SortedStack object will be instantiated and called as such:
- * var obj = new SortedStack()
- * obj.push(val)
- * obj.pop()
- * var param_3 = obj.peek()
- * var param_4 = obj.isEmpty()
- */
-```
-
-### **Go**
-
-```go
-type SortedStack struct {
- data []int
-}
-
-func Constructor() SortedStack {
- return SortedStack{make([]int, 0)}
-}
-
-func (s *SortedStack) Push(val int) {
- temp := make([]int, 0)
- for !s.IsEmpty() && s.Peek() < val {
- temp = append(temp, s.Peek())
- s.Pop()
- }
- s.data = append(s.data, val)
- for len(temp) > 0 {
- s.data = append(s.data, temp[len(temp)-1])
- temp = temp[:len(temp)-1]
- }
-}
-
-func (s *SortedStack) Pop() {
- if !s.IsEmpty() {
- s.data = s.data[:len(s.data)-1]
- }
-}
-
-func (s *SortedStack) Peek() int {
- if !s.IsEmpty() {
- return s.data[len(s.data)-1]
- }
- return -1
-}
-
-func (s *SortedStack) IsEmpty() bool {
- return len(s.data) == 0
-}
-```
-
-### **Rust**
-
```rust
use std::collections::VecDeque;
struct SortedStack {
@@ -294,10 +244,54 @@ impl SortedStack {
*/
```
-### **...**
+
-```
+### Solution 2
+
+
+```ts
+class SortedStack {
+ private stack: number[];
+
+ constructor() {
+ this.stack = [];
+ }
+
+ push(val: number): void {
+ if (this.isEmpty() || this.peek() > val) {
+ this.stack.push(val);
+ return;
+ }
+
+ const tmp = this.stack.pop();
+ this.push(val);
+ this.stack.push(tmp);
+ }
+
+ pop(): void {
+ this.stack.pop();
+ }
+
+ peek(): number {
+ return this.stack[this.stack.length - 1] ?? -1;
+ }
+
+ isEmpty(): boolean {
+ return this.stack.length === 0;
+ }
+}
+
+/**
+ * Your SortedStack object will be instantiated and called as such:
+ * var obj = new SortedStack()
+ * obj.push(val)
+ * obj.pop()
+ * var param_3 = obj.peek()
+ * var param_4 = obj.isEmpty()
+ */
```
+
+
diff --git a/lcci/03.06.Animal Shelter/README.md b/lcci/03.06.Animal Shelter/README.md
index 5d4a155d6025f..a28d24ebe5d8a 100644
--- a/lcci/03.06.Animal Shelter/README.md
+++ b/lcci/03.06.Animal Shelter/README.md
@@ -37,16 +37,10 @@
## 解法
-
-
-双队列存储。
+### 方法一
-### **Python3**
-
-
-
```python
class AnimalShelf:
def __init__(self):
@@ -81,10 +75,6 @@ class AnimalShelf:
# param_4 = obj.dequeueCat()
```
-### **Java**
-
-
-
```java
class AnimalShelf {
Queue cats;
@@ -128,8 +118,6 @@ class AnimalShelf {
*/
```
-### **TypeScript**
-
```ts
class AnimalShelf {
private cats: number[];
@@ -183,8 +171,6 @@ class AnimalShelf {
*/
```
-### **Rust**
-
```rust
use std::collections::VecDeque;
@@ -247,10 +233,6 @@ impl AnimalShelf {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/03.06.Animal Shelter/README_EN.md b/lcci/03.06.Animal Shelter/README_EN.md
index 3f53f4c513682..1c30d258238c7 100644
--- a/lcci/03.06.Animal Shelter/README_EN.md
+++ b/lcci/03.06.Animal Shelter/README_EN.md
@@ -50,9 +50,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class AnimalShelf:
@@ -88,8 +88,6 @@ class AnimalShelf:
# param_4 = obj.dequeueCat()
```
-### **Java**
-
```java
class AnimalShelf {
Queue cats;
@@ -133,8 +131,6 @@ class AnimalShelf {
*/
```
-### **TypeScript**
-
```ts
class AnimalShelf {
private cats: number[];
@@ -188,8 +184,6 @@ class AnimalShelf {
*/
```
-### **Rust**
-
```rust
use std::collections::VecDeque;
@@ -252,10 +246,6 @@ impl AnimalShelf {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.01.Route Between Nodes/README.md b/lcci/04.01.Route Between Nodes/README.md
index a6d2d179b7517..416d4a185f54f 100644
--- a/lcci/04.01.Route Between Nodes/README.md
+++ b/lcci/04.01.Route Between Nodes/README.md
@@ -29,18 +29,10 @@
## 解法
-
-
-**方法一:DFS**
-
-**方法二:BFS**
+### 方法一:DFS
-### **Python3**
-
-
-
```python
class Solution:
def findWhetherExistsPath(
@@ -63,31 +55,6 @@ class Solution:
return dfs(start)
```
-```python
-class Solution:
- def findWhetherExistsPath(
- self, n: int, graph: List[List[int]], start: int, target: int
- ) -> bool:
- g = defaultdict(list)
- for u, v in graph:
- g[u].append(v)
- q = deque([start])
- vis = {start}
- while q:
- u = q.popleft()
- if u == target:
- return True
- for v in g[u]:
- if v not in vis:
- vis.add(v)
- q.append(v)
- return False
-```
-
-### **Java**
-
-
-
```java
class Solution {
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
@@ -117,6 +84,83 @@ class Solution {
}
```
+```cpp
+class Solution {
+public:
+ bool findWhetherExistsPath(int n, vector>& graph, int start, int target) {
+ unordered_map> g;
+ for (auto& e : graph) g[e[0]].push_back(e[1]);
+ unordered_set vis{{start}};
+ return dfs(start, target, g, vis);
+ }
+
+ bool dfs(int u, int& target, unordered_map>& g, unordered_set& vis) {
+ if (u == target) return true;
+ for (int& v : g[u]) {
+ if (!vis.count(v)) {
+ vis.insert(v);
+ if (dfs(v, target, g, vis)) return true;
+ }
+ }
+ return false;
+ }
+};
+```
+
+```go
+func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool {
+ g := map[int][]int{}
+ for _, e := range graph {
+ u, v := e[0], e[1]
+ g[u] = append(g[u], v)
+ }
+ vis := map[int]bool{start: true}
+ var dfs func(int) bool
+ dfs = func(u int) bool {
+ if u == target {
+ return true
+ }
+ for _, v := range g[u] {
+ if !vis[v] {
+ vis[v] = true
+ if dfs(v) {
+ return true
+ }
+ }
+ }
+ return false
+ }
+ return dfs(start)
+}
+```
+
+
+
+### 方法二:BFS
+
+
+
+```python
+class Solution:
+ def findWhetherExistsPath(
+ self, n: int, graph: List[List[int]], start: int, target: int
+ ) -> bool:
+ g = defaultdict(list)
+ for u, v in graph:
+ g[u].append(v)
+ q = deque([start])
+ vis = {start}
+ while q:
+ u = q.popleft()
+ if u == target:
+ return True
+ for v in g[u]:
+ if v not in vis:
+ vis.add(v)
+ q.append(v)
+ return False
+```
+
```java
class Solution {
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
@@ -145,31 +189,6 @@ class Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- bool findWhetherExistsPath(int n, vector>& graph, int start, int target) {
- unordered_map> g;
- for (auto& e : graph) g[e[0]].push_back(e[1]);
- unordered_set vis{{start}};
- return dfs(start, target, g, vis);
- }
-
- bool dfs(int u, int& target, unordered_map>& g, unordered_set& vis) {
- if (u == target) return true;
- for (int& v : g[u]) {
- if (!vis.count(v)) {
- vis.insert(v);
- if (dfs(v, target, g, vis)) return true;
- }
- }
- return false;
- }
-};
-```
-
```cpp
class Solution {
public:
@@ -194,35 +213,6 @@ public:
};
```
-### **Go**
-
-```go
-func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool {
- g := map[int][]int{}
- for _, e := range graph {
- u, v := e[0], e[1]
- g[u] = append(g[u], v)
- }
- vis := map[int]bool{start: true}
- var dfs func(int) bool
- dfs = func(u int) bool {
- if u == target {
- return true
- }
- for _, v := range g[u] {
- if !vis[v] {
- vis[v] = true
- if dfs(v) {
- return true
- }
- }
- }
- return false
- }
- return dfs(start)
-}
-```
-
```go
func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool {
g := map[int][]int{}
@@ -249,10 +239,6 @@ func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.01.Route Between Nodes/README_EN.md b/lcci/04.01.Route Between Nodes/README_EN.md
index 15b7c64a0d238..d454199ccce1b 100644
--- a/lcci/04.01.Route Between Nodes/README_EN.md
+++ b/lcci/04.01.Route Between Nodes/README_EN.md
@@ -36,12 +36,10 @@
## Solutions
-DFS or BFS.
+### Solution 1
-### **Python3**
-
```python
class Solution:
def findWhetherExistsPath(
@@ -64,29 +62,6 @@ class Solution:
return dfs(start)
```
-```python
-class Solution:
- def findWhetherExistsPath(
- self, n: int, graph: List[List[int]], start: int, target: int
- ) -> bool:
- g = defaultdict(list)
- for u, v in graph:
- g[u].append(v)
- q = deque([start])
- vis = {start}
- while q:
- u = q.popleft()
- if u == target:
- return True
- for v in g[u]:
- if v not in vis:
- vis.add(v)
- q.append(v)
- return False
-```
-
-### **Java**
-
```java
class Solution {
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
@@ -116,6 +91,83 @@ class Solution {
}
```
+```cpp
+class Solution {
+public:
+ bool findWhetherExistsPath(int n, vector>& graph, int start, int target) {
+ unordered_map> g;
+ for (auto& e : graph) g[e[0]].push_back(e[1]);
+ unordered_set vis{{start}};
+ return dfs(start, target, g, vis);
+ }
+
+ bool dfs(int u, int& target, unordered_map>& g, unordered_set& vis) {
+ if (u == target) return true;
+ for (int& v : g[u]) {
+ if (!vis.count(v)) {
+ vis.insert(v);
+ if (dfs(v, target, g, vis)) return true;
+ }
+ }
+ return false;
+ }
+};
+```
+
+```go
+func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool {
+ g := map[int][]int{}
+ for _, e := range graph {
+ u, v := e[0], e[1]
+ g[u] = append(g[u], v)
+ }
+ vis := map[int]bool{start: true}
+ var dfs func(int) bool
+ dfs = func(u int) bool {
+ if u == target {
+ return true
+ }
+ for _, v := range g[u] {
+ if !vis[v] {
+ vis[v] = true
+ if dfs(v) {
+ return true
+ }
+ }
+ }
+ return false
+ }
+ return dfs(start)
+}
+```
+
+
+
+### Solution 2
+
+
+
+```python
+class Solution:
+ def findWhetherExistsPath(
+ self, n: int, graph: List[List[int]], start: int, target: int
+ ) -> bool:
+ g = defaultdict(list)
+ for u, v in graph:
+ g[u].append(v)
+ q = deque([start])
+ vis = {start}
+ while q:
+ u = q.popleft()
+ if u == target:
+ return True
+ for v in g[u]:
+ if v not in vis:
+ vis.add(v)
+ q.append(v)
+ return False
+```
+
```java
class Solution {
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
@@ -144,31 +196,6 @@ class Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- bool findWhetherExistsPath(int n, vector>& graph, int start, int target) {
- unordered_map> g;
- for (auto& e : graph) g[e[0]].push_back(e[1]);
- unordered_set vis{{start}};
- return dfs(start, target, g, vis);
- }
-
- bool dfs(int u, int& target, unordered_map>& g, unordered_set& vis) {
- if (u == target) return true;
- for (int& v : g[u]) {
- if (!vis.count(v)) {
- vis.insert(v);
- if (dfs(v, target, g, vis)) return true;
- }
- }
- return false;
- }
-};
-```
-
```cpp
class Solution {
public:
@@ -193,35 +220,6 @@ public:
};
```
-### **Go**
-
-```go
-func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool {
- g := map[int][]int{}
- for _, e := range graph {
- u, v := e[0], e[1]
- g[u] = append(g[u], v)
- }
- vis := map[int]bool{start: true}
- var dfs func(int) bool
- dfs = func(u int) bool {
- if u == target {
- return true
- }
- for _, v := range g[u] {
- if !vis[v] {
- vis[v] = true
- if dfs(v) {
- return true
- }
- }
- }
- return false
- }
- return dfs(start)
-}
-```
-
```go
func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool {
g := map[int][]int{}
@@ -248,10 +246,6 @@ func findWhetherExistsPath(n int, graph [][]int, start int, target int) bool {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.02.Minimum Height Tree/README.md b/lcci/04.02.Minimum Height Tree/README.md
index 9f6f9110fe962..abfa8036b3671 100644
--- a/lcci/04.02.Minimum Height Tree/README.md
+++ b/lcci/04.02.Minimum Height Tree/README.md
@@ -9,9 +9,7 @@
## 解法
-
-
-**方法一:递归**
+### 方法一:递归
先找到数组的中间点,作为二叉搜索树的根节点,然后递归左右子树即可。
@@ -19,10 +17,6 @@
-### **Python3**
-
-
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -43,10 +37,6 @@ class Solution:
return dfs(0, len(nums) - 1)
```
-### **Java**
-
-
-
```java
/**
* Definition for a binary tree node.
@@ -75,8 +65,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -100,8 +88,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -125,8 +111,6 @@ func sortedArrayToBST(nums []int) *TreeNode {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -154,8 +138,6 @@ function sortedArrayToBST(nums: number[]): TreeNode | null {
}
```
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -200,8 +182,6 @@ impl Solution {
}
```
-### **JavaScript**
-
```js
/**
* Definition for a binary tree node.
@@ -227,10 +207,6 @@ var sortedArrayToBST = function (nums) {
};
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.02.Minimum Height Tree/README_EN.md b/lcci/04.02.Minimum Height Tree/README_EN.md
index 0efe11ae86e63..38a6ace638a0f 100644
--- a/lcci/04.02.Minimum Height Tree/README_EN.md
+++ b/lcci/04.02.Minimum Height Tree/README_EN.md
@@ -32,9 +32,9 @@ One possible answer is: [0,-3,9,-10,null,5],which represents the following tre
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for a binary tree node.
@@ -56,8 +56,6 @@ class Solution:
return dfs(0, len(nums) - 1)
```
-### **Java**
-
```java
/**
* Definition for a binary tree node.
@@ -86,8 +84,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -111,8 +107,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -136,8 +130,6 @@ func sortedArrayToBST(nums []int) *TreeNode {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -165,8 +157,6 @@ function sortedArrayToBST(nums: number[]): TreeNode | null {
}
```
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -211,8 +201,6 @@ impl Solution {
}
```
-### **JavaScript**
-
```js
/**
* Definition for a binary tree node.
@@ -238,10 +226,6 @@ var sortedArrayToBST = function (nums) {
};
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.03.List of Depth/README.md b/lcci/04.03.List of Depth/README.md
index bcd2566820b68..4f376f7eeedc7 100644
--- a/lcci/04.03.List of Depth/README.md
+++ b/lcci/04.03.List of Depth/README.md
@@ -26,9 +26,7 @@
## 解法
-
-
-**方法一:BFS 层序遍历**
+### 方法一:BFS 层序遍历
我们可以使用 BFS 层序遍历的方法,每次遍历一层,将当前层的节点值存入链表中,然后将链表加入到结果数组中。
@@ -36,10 +34,6 @@
-### **Python3**
-
-
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -73,10 +67,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
/**
* Definition for a binary tree node.
@@ -121,8 +111,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -168,8 +156,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -209,8 +195,6 @@ func listOfDepth(tree *TreeNode) (ans []*ListNode) {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -257,8 +241,6 @@ function listOfDepth(tree: TreeNode | null): Array {
}
```
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -329,10 +311,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.03.List of Depth/README_EN.md b/lcci/04.03.List of Depth/README_EN.md
index 777bb88b47104..16d2fab33123c 100644
--- a/lcci/04.03.List of Depth/README_EN.md
+++ b/lcci/04.03.List of Depth/README_EN.md
@@ -38,12 +38,10 @@
## Solutions
-Level order traversal.
+### Solution 1
-### **Python3**
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -77,8 +75,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
/**
* Definition for a binary tree node.
@@ -123,8 +119,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -170,8 +164,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -211,8 +203,6 @@ func listOfDepth(tree *TreeNode) (ans []*ListNode) {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -259,8 +249,6 @@ function listOfDepth(tree: TreeNode | null): Array {
}
```
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -331,10 +319,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.04.Check Balance/README.md b/lcci/04.04.Check Balance/README.md
index 2c1febf77db45..625b40f3cb5e3 100644
--- a/lcci/04.04.Check Balance/README.md
+++ b/lcci/04.04.Check Balance/README.md
@@ -9,9 +9,7 @@
## 解法
-
-
-**方法一:递归(后序遍历)**
+### 方法一:递归(后序遍历)
我们设计一个函数 $dfs(root)$,它的作用是返回以 $root$ 为根节点的树的高度,如果以 $root$ 为根节点的树是平衡树,则返回树的高度,否则返回 $-1$。
@@ -26,10 +24,6 @@
-### **Python3**
-
-
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -51,32 +45,6 @@ class Solution:
return dfs(root)[1]
```
-```python
-# Definition for a binary tree node.
-# class TreeNode:
-# def __init__(self, x):
-# self.val = x
-# self.left = None
-# self.right = None
-
-
-class Solution:
- def isBalanced(self, root: TreeNode) -> bool:
- def dfs(root: TreeNode):
- if root is None:
- return 0
- l, r = dfs(root.left), dfs(root.right)
- if l == -1 or r == -1 or abs(l - r) > 1:
- return -1
- return max(l, r) + 1
-
- return dfs(root) >= 0
-```
-
-### **Java**
-
-
-
```java
/**
* Definition for a binary tree node.
@@ -106,8 +74,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -137,8 +103,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -171,8 +135,6 @@ func abs(x int) int {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -204,10 +166,34 @@ function isBalanced(root: TreeNode | null): boolean {
}
```
-### **...**
+
-```
+### 方法二
+
+
+
+```python
+# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution:
+ def isBalanced(self, root: TreeNode) -> bool:
+ def dfs(root: TreeNode):
+ if root is None:
+ return 0
+ l, r = dfs(root.left), dfs(root.right)
+ if l == -1 or r == -1 or abs(l - r) > 1:
+ return -1
+ return max(l, r) + 1
+
+ return dfs(root) >= 0
```
+
+
diff --git a/lcci/04.04.Check Balance/README_EN.md b/lcci/04.04.Check Balance/README_EN.md
index 9a6c3d85181f8..77c2c17fa6097 100644
--- a/lcci/04.04.Check Balance/README_EN.md
+++ b/lcci/04.04.Check Balance/README_EN.md
@@ -52,9 +52,9 @@ return false.
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for a binary tree node.
@@ -77,30 +77,6 @@ class Solution:
return dfs(root)[1]
```
-```python
-# Definition for a binary tree node.
-# class TreeNode:
-# def __init__(self, x):
-# self.val = x
-# self.left = None
-# self.right = None
-
-
-class Solution:
- def isBalanced(self, root: TreeNode) -> bool:
- def dfs(root: TreeNode):
- if root is None:
- return 0
- l, r = dfs(root.left), dfs(root.right)
- if l == -1 or r == -1 or abs(l - r) > 1:
- return -1
- return max(l, r) + 1
-
- return dfs(root) >= 0
-```
-
-### **Java**
-
```java
/**
* Definition for a binary tree node.
@@ -130,8 +106,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -161,8 +135,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -195,8 +167,6 @@ func abs(x int) int {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -228,10 +198,34 @@ function isBalanced(root: TreeNode | null): boolean {
}
```
-### **...**
+
+
+### Solution 2
-```
+
+
+```python
+# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution:
+ def isBalanced(self, root: TreeNode) -> bool:
+ def dfs(root: TreeNode):
+ if root is None:
+ return 0
+ l, r = dfs(root.left), dfs(root.right)
+ if l == -1 or r == -1 or abs(l - r) > 1:
+ return -1
+ return max(l, r) + 1
+
+ return dfs(root) >= 0
```
+
+
diff --git a/lcci/04.05.Legal Binary Search Tree/README.md b/lcci/04.05.Legal Binary Search Tree/README.md
index 0629955c169d7..daa93ce0f171a 100644
--- a/lcci/04.05.Legal Binary Search Tree/README.md
+++ b/lcci/04.05.Legal Binary Search Tree/README.md
@@ -9,16 +9,10 @@
## 解法
-
-
-一棵合法的二叉搜索树,其中序遍历的结果应该升序排列。
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -47,10 +41,6 @@ class Solution:
self.isValid(root.right)
```
-### **Java**
-
-
-
```java
/**
* Definition for a binary tree node.
@@ -85,53 +75,6 @@ class Solution {
}
```
-### **Go**
-
-- 非递归中序遍历
-
-```go
-func isValidBST(root *TreeNode) bool {
- stack := make([]*TreeNode, 0)
- var prev *TreeNode = nil
- node := root
- for len(stack) > 0 || node != nil {
- for node != nil {
- stack = append(stack, node)
- node = node.Left
- }
- node = stack[len(stack)-1]
- stack = stack[:len(stack)-1]
- if prev == nil || node.Val > prev.Val {
- prev = node
- } else {
- return false
- }
- node = node.Right
- }
- return true
-}
-```
-
-- 利用上界下界判定
-
-```go
-func isValidBST(root *TreeNode) bool {
- return check(root, math.MinInt64, math.MaxInt64)
-}
-
-func check(node *TreeNode, lower, upper int) bool {
- if node == nil {
- return true
- }
- if node.Val <= lower || node.Val >= upper {
- return false
- }
- return check(node.Left, lower, node.Val) && check(node.Right, node.Val, upper)
-}
-```
-
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -167,7 +110,28 @@ public:
};
```
-### **TypeScript**
+```go
+func isValidBST(root *TreeNode) bool {
+ stack := make([]*TreeNode, 0)
+ var prev *TreeNode = nil
+ node := root
+ for len(stack) > 0 || node != nil {
+ for node != nil {
+ stack = append(stack, node)
+ node = node.Left
+ }
+ node = stack[len(stack)-1]
+ stack = stack[:len(stack)-1]
+ if prev == nil || node.Val > prev.Val {
+ prev = node
+ } else {
+ return false
+ }
+ node = node.Right
+ }
+ return true
+}
+```
```ts
/**
@@ -201,42 +165,6 @@ function isValidBST(root: TreeNode | null): boolean {
}
```
-```ts
-/**
- * Definition for a binary tree node.
- * class TreeNode {
- * val: number
- * left: TreeNode | null
- * right: TreeNode | null
- * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
- * this.val = (val===undefined ? 0 : val)
- * this.left = (left===undefined ? null : left)
- * this.right = (right===undefined ? null : right)
- * }
- * }
- */
-
-function isValidBST(root: TreeNode | null): boolean {
- if (root == null) {
- return true;
- }
- const { val, left, right } = root;
- const dfs = (root: TreeNode | null, min: number, max: number) => {
- if (root == null) {
- return true;
- }
- const { val, left, right } = root;
- if (val <= min || val >= max) {
- return false;
- }
- return dfs(left, min, Math.min(val, max)) && dfs(right, Math.max(val, min), max);
- };
- return dfs(left, -Infinity, val) && dfs(right, val, Infinity);
-}
-```
-
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -280,10 +208,62 @@ impl Solution {
}
```
-### **...**
+
+### 方法二
+
+
+
+```go
+func isValidBST(root *TreeNode) bool {
+ return check(root, math.MinInt64, math.MaxInt64)
+}
+
+func check(node *TreeNode, lower, upper int) bool {
+ if node == nil {
+ return true
+ }
+ if node.Val <= lower || node.Val >= upper {
+ return false
+ }
+ return check(node.Left, lower, node.Val) && check(node.Right, node.Val, upper)
+}
```
+```ts
+/**
+ * Definition for a binary tree node.
+ * class TreeNode {
+ * val: number
+ * left: TreeNode | null
+ * right: TreeNode | null
+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ * }
+ */
+
+function isValidBST(root: TreeNode | null): boolean {
+ if (root == null) {
+ return true;
+ }
+ const { val, left, right } = root;
+ const dfs = (root: TreeNode | null, min: number, max: number) => {
+ if (root == null) {
+ return true;
+ }
+ const { val, left, right } = root;
+ if (val <= min || val >= max) {
+ return false;
+ }
+ return dfs(left, min, Math.min(val, max)) && dfs(right, Math.max(val, min), max);
+ };
+ return dfs(left, -Infinity, val) && dfs(right, val, Infinity);
+}
```
+
+
diff --git a/lcci/04.05.Legal Binary Search Tree/README_EN.md b/lcci/04.05.Legal Binary Search Tree/README_EN.md
index 2c0a7442c4c83..668b007c4f421 100644
--- a/lcci/04.05.Legal Binary Search Tree/README_EN.md
+++ b/lcci/04.05.Legal Binary Search Tree/README_EN.md
@@ -46,9 +46,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for a binary tree node.
@@ -78,8 +78,6 @@ class Solution:
self.isValid(root.right)
```
-### **Java**
-
```java
/**
* Definition for a binary tree node.
@@ -114,53 +112,6 @@ class Solution {
}
```
-### **Go**
-
-- Non-recursive in-order traversal
-
-```go
-func isValidBST(root *TreeNode) bool {
- stack := make([]*TreeNode, 0)
- var prev *TreeNode = nil
- node := root
- for len(stack) > 0 || node != nil {
- for node != nil {
- stack = append(stack, node)
- node = node.Left
- }
- node = stack[len(stack)-1]
- stack = stack[:len(stack)-1]
- if prev == nil || node.Val > prev.Val {
- prev = node
- } else {
- return false
- }
- node = node.Right
- }
- return true
-}
-```
-
-- Use upper bound and lower bound to check
-
-```go
-func isValidBST(root *TreeNode) bool {
- return check(root, math.MinInt64, math.MaxInt64)
-}
-
-func check(node *TreeNode, lower, upper int) bool {
- if node == nil {
- return true
- }
- if node.Val <= lower || node.Val >= upper {
- return false
- }
- return check(node.Left, lower, node.Val) && check(node.Right, node.Val, upper)
-}
-```
-
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -196,7 +147,28 @@ public:
};
```
-### **TypeScript**
+```go
+func isValidBST(root *TreeNode) bool {
+ stack := make([]*TreeNode, 0)
+ var prev *TreeNode = nil
+ node := root
+ for len(stack) > 0 || node != nil {
+ for node != nil {
+ stack = append(stack, node)
+ node = node.Left
+ }
+ node = stack[len(stack)-1]
+ stack = stack[:len(stack)-1]
+ if prev == nil || node.Val > prev.Val {
+ prev = node
+ } else {
+ return false
+ }
+ node = node.Right
+ }
+ return true
+}
+```
```ts
/**
@@ -230,42 +202,6 @@ function isValidBST(root: TreeNode | null): boolean {
}
```
-```ts
-/**
- * Definition for a binary tree node.
- * class TreeNode {
- * val: number
- * left: TreeNode | null
- * right: TreeNode | null
- * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
- * this.val = (val===undefined ? 0 : val)
- * this.left = (left===undefined ? null : left)
- * this.right = (right===undefined ? null : right)
- * }
- * }
- */
-
-function isValidBST(root: TreeNode | null): boolean {
- if (root == null) {
- return true;
- }
- const { val, left, right } = root;
- const dfs = (root: TreeNode | null, min: number, max: number) => {
- if (root == null) {
- return true;
- }
- const { val, left, right } = root;
- if (val <= min || val >= max) {
- return false;
- }
- return dfs(left, min, Math.min(val, max)) && dfs(right, Math.max(val, min), max);
- };
- return dfs(left, -Infinity, val) && dfs(right, val, Infinity);
-}
-```
-
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -309,10 +245,62 @@ impl Solution {
}
```
-### **...**
+
+
+### Solution 2
+
+
+```go
+func isValidBST(root *TreeNode) bool {
+ return check(root, math.MinInt64, math.MaxInt64)
+}
+
+func check(node *TreeNode, lower, upper int) bool {
+ if node == nil {
+ return true
+ }
+ if node.Val <= lower || node.Val >= upper {
+ return false
+ }
+ return check(node.Left, lower, node.Val) && check(node.Right, node.Val, upper)
+}
```
+```ts
+/**
+ * Definition for a binary tree node.
+ * class TreeNode {
+ * val: number
+ * left: TreeNode | null
+ * right: TreeNode | null
+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
+ * this.val = (val===undefined ? 0 : val)
+ * this.left = (left===undefined ? null : left)
+ * this.right = (right===undefined ? null : right)
+ * }
+ * }
+ */
+
+function isValidBST(root: TreeNode | null): boolean {
+ if (root == null) {
+ return true;
+ }
+ const { val, left, right } = root;
+ const dfs = (root: TreeNode | null, min: number, max: number) => {
+ if (root == null) {
+ return true;
+ }
+ const { val, left, right } = root;
+ if (val <= min || val >= max) {
+ return false;
+ }
+ return dfs(left, min, Math.min(val, max)) && dfs(right, Math.max(val, min), max);
+ };
+ return dfs(left, -Infinity, val) && dfs(right, val, Infinity);
+}
```
+
+
diff --git a/lcci/04.06.Successor/README.md b/lcci/04.06.Successor/README.md
index 6b3c7828ddbad..738d9e84b6456 100644
--- a/lcci/04.06.Successor/README.md
+++ b/lcci/04.06.Successor/README.md
@@ -35,14 +35,10 @@
## 解法
-
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -69,10 +65,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
/**
* Definition for a binary tree node.
@@ -110,8 +102,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -144,41 +134,6 @@ public:
};
```
-```cpp
-/**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
-class Solution {
-public:
- TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
- stack stk;
- TreeNode* cur = root;
- while (cur != nullptr || !stk.empty()) {
- if (cur == nullptr) {
- cur = stk.top();
- stk.pop();
- if (cur->val > p->val) {
- return cur;
- }
- cur = cur->right;
- } else {
- stk.push(cur);
- cur = cur->left;
- }
- }
- return cur;
- }
-};
-```
-
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -207,8 +162,6 @@ func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
}
```
-### **JavaScript**
-
```js
/**
* Definition for a binary tree node.
@@ -238,6 +191,45 @@ var inorderSuccessor = function (root, p) {
};
```
+
+
+### 方法二
+
+
+
+```cpp
+/**
+ * Definition for a binary tree node.
+ * struct TreeNode {
+ * int val;
+ * TreeNode *left;
+ * TreeNode *right;
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
+ * };
+ */
+class Solution {
+public:
+ TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
+ stack stk;
+ TreeNode* cur = root;
+ while (cur != nullptr || !stk.empty()) {
+ if (cur == nullptr) {
+ cur = stk.top();
+ stk.pop();
+ if (cur->val > p->val) {
+ return cur;
+ }
+ cur = cur->right;
+ } else {
+ stk.push(cur);
+ cur = cur->left;
+ }
+ }
+ return cur;
+ }
+};
+```
+
```js
/**
* Definition for a binary tree node.
@@ -270,10 +262,6 @@ var inorderSuccessor = function (root, p) {
};
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.06.Successor/README_EN.md b/lcci/04.06.Successor/README_EN.md
index ce332bda5025a..3bba52a9e2c87 100644
--- a/lcci/04.06.Successor/README_EN.md
+++ b/lcci/04.06.Successor/README_EN.md
@@ -54,9 +54,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for a binary tree node.
@@ -84,8 +84,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
/**
* Definition for a binary tree node.
@@ -123,8 +121,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -157,41 +153,6 @@ public:
};
```
-```cpp
-/**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
-class Solution {
-public:
- TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
- stack stk;
- TreeNode* cur = root;
- while (cur != nullptr || !stk.empty()) {
- if (cur == nullptr) {
- cur = stk.top();
- stk.pop();
- if (cur->val > p->val) {
- return cur;
- }
- cur = cur->right;
- } else {
- stk.push(cur);
- cur = cur->left;
- }
- }
- return cur;
- }
-};
-```
-
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -220,8 +181,6 @@ func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
}
```
-### **JavaScript**
-
```js
/**
* Definition for a binary tree node.
@@ -251,6 +210,45 @@ var inorderSuccessor = function (root, p) {
};
```
+
+
+### Solution 2
+
+
+
+```cpp
+/**
+ * Definition for a binary tree node.
+ * struct TreeNode {
+ * int val;
+ * TreeNode *left;
+ * TreeNode *right;
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
+ * };
+ */
+class Solution {
+public:
+ TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
+ stack stk;
+ TreeNode* cur = root;
+ while (cur != nullptr || !stk.empty()) {
+ if (cur == nullptr) {
+ cur = stk.top();
+ stk.pop();
+ if (cur->val > p->val) {
+ return cur;
+ }
+ cur = cur->right;
+ } else {
+ stk.push(cur);
+ cur = cur->left;
+ }
+ }
+ return cur;
+ }
+};
+```
+
```js
/**
* Definition for a binary tree node.
@@ -283,10 +281,6 @@ var inorderSuccessor = function (root, p) {
};
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.08.First Common Ancestor/README.md b/lcci/04.08.First Common Ancestor/README.md
index c90da4486c038..939bd3d854f2a 100644
--- a/lcci/04.08.First Common Ancestor/README.md
+++ b/lcci/04.08.First Common Ancestor/README.md
@@ -9,14 +9,10 @@
## 解法
-
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -37,10 +33,6 @@ class Solution:
return right if left is None else (left if right is None else root)
```
-### **Java**
-
-
-
```java
/**
* Definition for a binary tree node.
@@ -63,10 +55,6 @@ class Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.08.First Common Ancestor/README_EN.md b/lcci/04.08.First Common Ancestor/README_EN.md
index 6f141303039e9..6d107c5687b76 100644
--- a/lcci/04.08.First Common Ancestor/README_EN.md
+++ b/lcci/04.08.First Common Ancestor/README_EN.md
@@ -55,9 +55,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
# Definition for a binary tree node.
@@ -79,8 +79,6 @@ class Solution:
return right if left is None else (left if right is None else root)
```
-### **Java**
-
```java
/**
* Definition for a binary tree node.
@@ -103,10 +101,6 @@ class Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.09.BST Sequences/README.md b/lcci/04.09.BST Sequences/README.md
index 9f7236dda3297..291f2f20b3c9b 100644
--- a/lcci/04.09.BST Sequences/README.md
+++ b/lcci/04.09.BST Sequences/README.md
@@ -21,30 +21,4 @@
## 解法
-
-
-
-
-### **Python3**
-
-
-
-```python
-
-```
-
-### **Java**
-
-
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/04.09.BST Sequences/README_EN.md b/lcci/04.09.BST Sequences/README_EN.md
index 0b5eaa8733f95..87ab50a4832d1 100644
--- a/lcci/04.09.BST Sequences/README_EN.md
+++ b/lcci/04.09.BST Sequences/README_EN.md
@@ -31,24 +31,4 @@ Given the following tree:
## Solutions
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/04.10.Check SubTree/README.md b/lcci/04.10.Check SubTree/README.md
index 5cee3c2b1cd5b..fe52620d24a15 100644
--- a/lcci/04.10.Check SubTree/README.md
+++ b/lcci/04.10.Check SubTree/README.md
@@ -29,14 +29,10 @@
## 解法
-
+### 方法一
-### **Python3**
-
-
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -60,10 +56,6 @@ class Solution:
return dfs(t1, t2)
```
-### **Java**
-
-
-
```java
/**
* Definition for a binary tree node.
@@ -90,8 +82,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -113,8 +103,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -138,8 +126,6 @@ func checkSubTree(t1 *TreeNode, t2 *TreeNode) bool {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -169,8 +155,6 @@ function checkSubTree(t1: TreeNode | null, t2: TreeNode | null): boolean {
}
```
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -217,10 +201,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.10.Check SubTree/README_EN.md b/lcci/04.10.Check SubTree/README_EN.md
index c698de234fc93..b1435c469cd46 100644
--- a/lcci/04.10.Check SubTree/README_EN.md
+++ b/lcci/04.10.Check SubTree/README_EN.md
@@ -36,12 +36,10 @@
## Solutions
-Find the t2 node in t1 first, then use the depth-first search (DFS) algorithm to make sure that the subtree and the subtree of t2 are identical, otherwise return FALSE.
+### Solution 1
-### **Python3**
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -65,8 +63,6 @@ class Solution:
return dfs(t1, t2)
```
-### **Java**
-
```java
/**
* Definition for a binary tree node.
@@ -93,8 +89,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -116,8 +110,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -141,8 +133,6 @@ func checkSubTree(t1 *TreeNode, t2 *TreeNode) bool {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -172,8 +162,6 @@ function checkSubTree(t1: TreeNode | null, t2: TreeNode | null): boolean {
}
```
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -220,10 +208,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.12.Paths with Sum/README.md b/lcci/04.12.Paths with Sum/README.md
index 25e66de267188..6a4a33e6a2bb6 100644
--- a/lcci/04.12.Paths with Sum/README.md
+++ b/lcci/04.12.Paths with Sum/README.md
@@ -32,9 +32,7 @@
## 解法
-
-
-**方法一:哈希表 + 前缀和 + 递归**
+### 方法一:哈希表 + 前缀和 + 递归
我们可以运用前缀和的思想,对二叉树进行递归遍历,同时用哈希表 $cnt$ 统计从根节点到当前节点的路径上各个前缀和出现的次数。
@@ -54,10 +52,6 @@
-### **Python3**
-
-
-
```python
# Definition for a binary tree node.
# class TreeNode:
@@ -84,10 +78,6 @@ class Solution:
return dfs(root, 0)
```
-### **Java**
-
-
-
```java
/**
* Definition for a binary tree node.
@@ -123,8 +113,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -157,8 +145,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -187,8 +173,6 @@ func pathSum(root *TreeNode, sum int) int {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -223,8 +207,6 @@ function pathSum(root: TreeNode | null, sum: number): number {
}
```
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -275,10 +257,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/04.12.Paths with Sum/README_EN.md b/lcci/04.12.Paths with Sum/README_EN.md
index f75af32d6e481..a51f4d2b92bb2 100644
--- a/lcci/04.12.Paths with Sum/README_EN.md
+++ b/lcci/04.12.Paths with Sum/README_EN.md
@@ -44,7 +44,7 @@ Given the following tree and sum = 22,
## Solutions
-**Solution 1: Hash Table + Prefix Sum + Recursion**
+### Solution 1: Hash Table + Prefix Sum + Recursion
We can use the idea of prefix sum to recursively traverse the binary tree, and use a hash table $cnt$ to count the occurrence of each prefix sum on the path from the root node to the current node.
@@ -64,32 +64,32 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is
-### **Python3**
-
```python
+# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
- def dfs(root, sum, flag):
- nonlocal ans
- if not root:
+ def dfs(root: TreeNode, s: int):
+ if root is None:
return 0
- if sum - root.val == 0:
- ans += 1
- if flag == 0:
- dfs(root.left, sum, 0)
- dfs(root.right, sum, 0)
- dfs(root.left, sum - root.val, 1)
- dfs(root.right, sum - root.val, 1)
-
- if not root:
- return 0
- ans = 0
- dfs(root, sum, 0)
- return ans
+ s += root.val
+ ans = cnt[s - sum]
+ cnt[s] += 1
+ ans += dfs(root.left, s)
+ ans += dfs(root.right, s)
+ cnt[s] -= 1
+ return ans
+
+ cnt = Counter({0: 1})
+ return dfs(root, 0)
```
-### **Java**
-
```java
/**
* Definition for a binary tree node.
@@ -125,8 +125,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
/**
* Definition for a binary tree node.
@@ -159,8 +157,6 @@ public:
};
```
-### **Go**
-
```go
/**
* Definition for a binary tree node.
@@ -189,8 +185,6 @@ func pathSum(root *TreeNode, sum int) int {
}
```
-### **TypeScript**
-
```ts
/**
* Definition for a binary tree node.
@@ -225,8 +219,6 @@ function pathSum(root: TreeNode | null, sum: number): number {
}
```
-### **Rust**
-
```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
@@ -277,10 +269,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.01.Insert Into Bits/README.md b/lcci/05.01.Insert Into Bits/README.md
index 1281bc7d196ed..7da656234d5db 100644
--- a/lcci/05.01.Insert Into Bits/README.md
+++ b/lcci/05.01.Insert Into Bits/README.md
@@ -24,9 +24,7 @@
## 解法
-
-
-**方法一:位运算**
+### 方法一:位运算
我们先将 $N$ 的第 $i$ 位到第 $j$ 位清零,然后再将 $M$ 左移 $i$ 位,最后将 $M$ 与 $N$ 进行或运算。
@@ -34,10 +32,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def insertBits(self, N: int, M: int, i: int, j: int) -> int:
@@ -46,10 +40,6 @@ class Solution:
return N | M << i
```
-### **Java**
-
-
-
```java
class Solution {
public int insertBits(int N, int M, int i, int j) {
@@ -61,8 +51,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -75,8 +63,6 @@ public:
};
```
-### **Go**
-
```go
func insertBits(N int, M int, i int, j int) int {
for k := i; k <= j; k++ {
@@ -86,8 +72,6 @@ func insertBits(N int, M int, i int, j int) int {
}
```
-### **TypeScript**
-
```ts
function insertBits(N: number, M: number, i: number, j: number): number {
for (let k = i; k <= j; ++k) {
@@ -97,10 +81,6 @@ function insertBits(N: number, M: number, i: number, j: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.01.Insert Into Bits/README_EN.md b/lcci/05.01.Insert Into Bits/README_EN.md
index 857c3c2e0ad13..27bf793f7844c 100644
--- a/lcci/05.01.Insert Into Bits/README_EN.md
+++ b/lcci/05.01.Insert Into Bits/README_EN.md
@@ -24,7 +24,7 @@
## Solutions
-**Solution 1: Bit Manipulation**
+### Solution 1: Bit Manipulation
First, we clear the bits from the $i$-th to the $j$-th in $N$, then we left shift $M$ by $i$ bits, and finally perform a bitwise OR operation on $M$ and $N$.
@@ -32,8 +32,6 @@ The time complexity is $O(\log n)$, where $n$ is the size of $N$. The space comp
-### **Python3**
-
```python
class Solution:
def insertBits(self, N: int, M: int, i: int, j: int) -> int:
@@ -42,8 +40,6 @@ class Solution:
return N | M << i
```
-### **Java**
-
```java
class Solution {
public int insertBits(int N, int M, int i, int j) {
@@ -55,8 +51,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -69,8 +63,6 @@ public:
};
```
-### **Go**
-
```go
func insertBits(N int, M int, i int, j int) int {
for k := i; k <= j; k++ {
@@ -80,8 +72,6 @@ func insertBits(N int, M int, i int, j int) int {
}
```
-### **TypeScript**
-
```ts
function insertBits(N: number, M: number, i: number, j: number): number {
for (let k = i; k <= j; ++k) {
@@ -91,10 +81,6 @@ function insertBits(N: number, M: number, i: number, j: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.02.Binary Number to String/README.md b/lcci/05.02.Binary Number to String/README.md
index c9fb169c662be..7d1fde5dd0ce0 100644
--- a/lcci/05.02.Binary Number to String/README.md
+++ b/lcci/05.02.Binary Number to String/README.md
@@ -23,9 +23,7 @@
## 解法
-
-
-**方法一:十进制小数转二进制小数**
+### 方法一:十进制小数转二进制小数
十进制小数转二进制小数的方法是:小数部分乘以 $2$,取整数部分作为二进制小数的下一位,小数部分作为下一次乘法的被乘数,直到小数部分为 $0$ 或者二进制小数的长度超过 $32$ 位。
@@ -50,10 +48,6 @@ $$
-### **Python3**
-
-
-
```python
class Solution:
def printBin(self, num: float) -> str:
@@ -66,10 +60,6 @@ class Solution:
return 'ERROR' if num else ans
```
-### **Java**
-
-
-
```java
class Solution {
public String printBin(double num) {
@@ -85,8 +75,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -103,8 +91,6 @@ public:
};
```
-### **Go**
-
```go
func printBin(num float64) string {
ans := &strings.Builder{}
@@ -122,10 +108,6 @@ func printBin(num float64) string {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.02.Binary Number to String/README_EN.md b/lcci/05.02.Binary Number to String/README_EN.md
index c32f00d1ca1f1..6d0d09b02a787 100644
--- a/lcci/05.02.Binary Number to String/README_EN.md
+++ b/lcci/05.02.Binary Number to String/README_EN.md
@@ -30,7 +30,7 @@
## Solutions
-**Solution 1: Decimal Fraction to Binary Fraction**
+### Solution 1: Decimal Fraction to Binary Fraction
The method of converting a decimal fraction to a binary fraction is as follows: multiply the decimal part by $2$, take the integer part as the next digit of the binary fraction, and take the decimal part as the multiplicand for the next multiplication, until the decimal part is $0$ or the length of the binary fraction exceeds $32$ bits.
@@ -55,8 +55,6 @@ The time complexity is $O(C)$, and the space complexity is $O(C)$. Here, $C$ is
-### **Python3**
-
```python
class Solution:
def printBin(self, num: float) -> str:
@@ -69,8 +67,6 @@ class Solution:
return 'ERROR' if num else ans
```
-### **Java**
-
```java
class Solution {
public String printBin(double num) {
@@ -86,8 +82,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -104,8 +98,6 @@ public:
};
```
-### **Go**
-
```go
func printBin(num float64) string {
ans := &strings.Builder{}
@@ -123,10 +115,6 @@ func printBin(num float64) string {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.03.Reverse Bits/README.md b/lcci/05.03.Reverse Bits/README.md
index 5f4b0e93c67ce..5a36599803832 100644
--- a/lcci/05.03.Reverse Bits/README.md
+++ b/lcci/05.03.Reverse Bits/README.md
@@ -18,9 +18,7 @@
## 解法
-
-
-**方法一:双指针**
+### 方法一:双指针
我们可以使用双指针 $i$ 和 $j$ 维护一个滑动窗口,其中 $i$ 为右指针,$j$ 为左指针。每次右指针 $i$ 向右移动一位,如果此时窗口内的 $0$ 的个数超过 $1$ 个,则左指针 $j$ 向右移动一位,直到窗口内的 $0$ 的个数不超过 $1$ 个为止。然后计算此时窗口的长度,与当前最大长度进行比较,取较大值作为当前最大长度。
@@ -30,10 +28,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def reverseBits(self, num: int) -> int:
@@ -47,10 +41,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
public int reverseBits(int num) {
@@ -68,8 +58,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -88,8 +76,6 @@ public:
};
```
-### **Go**
-
```go
func reverseBits(num int) (ans int) {
var cnt, j int
@@ -105,10 +91,6 @@ func reverseBits(num int) (ans int) {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.03.Reverse Bits/README_EN.md b/lcci/05.03.Reverse Bits/README_EN.md
index 35d6af400e1a5..522bad98b45aa 100644
--- a/lcci/05.03.Reverse Bits/README_EN.md
+++ b/lcci/05.03.Reverse Bits/README_EN.md
@@ -24,7 +24,7 @@
## Solutions
-**Solution 1: Two Pointers**
+### Solution 1: Two Pointers
We can use two pointers $i$ and $j$ to maintain a sliding window, where $i$ is the right pointer and $j$ is the left pointer. Each time the right pointer $i$ moves one bit to the right, if the number of $0$s in the window exceeds $1$, then the left pointer $j$ moves one bit to the right, until the number of $0$s in the window does not exceed $1$. Then calculate the length of the window at this time, compare it with the current maximum length, and take the larger value as the current maximum length.
@@ -34,8 +34,6 @@ The time complexity is $O(\log M)$, and the space complexity is $O(1)$. Here, $M
-### **Python3**
-
```python
class Solution:
def reverseBits(self, num: int) -> int:
@@ -49,8 +47,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
public int reverseBits(int num) {
@@ -68,8 +64,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -88,8 +82,6 @@ public:
};
```
-### **Go**
-
```go
func reverseBits(num int) (ans int) {
var cnt, j int
@@ -105,10 +97,6 @@ func reverseBits(num int) (ans int) {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.04.Closed Number/README.md b/lcci/05.04.Closed Number/README.md
index 34b543c3b4def..e0a7fa1d726de 100644
--- a/lcci/05.04.Closed Number/README.md
+++ b/lcci/05.04.Closed Number/README.md
@@ -25,9 +25,7 @@
## 解法
-
-
-**方法一:位运算**
+### 方法一:位运算
我们先考虑如何找出第一个比 $num$ 大且二进制表示中 $1$ 的个数相同的数。
@@ -43,10 +41,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def findClosedNumbers(self, num: int) -> List[int]:
@@ -73,10 +67,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
public int[] findClosedNumbers(int num) {
@@ -112,8 +102,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -150,8 +138,6 @@ public:
};
```
-### **Go**
-
```go
func findClosedNumbers(num int) []int {
ans := []int{-1, -1}
@@ -185,8 +171,6 @@ func findClosedNumbers(num int) []int {
}
```
-### **TypeScript**
-
```ts
function findClosedNumbers(num: number): number[] {
const ans: number[] = [-1, -1];
@@ -220,10 +204,6 @@ function findClosedNumbers(num: number): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.04.Closed Number/README_EN.md b/lcci/05.04.Closed Number/README_EN.md
index 199049cfb5362..f21b917ab7591 100644
--- a/lcci/05.04.Closed Number/README_EN.md
+++ b/lcci/05.04.Closed Number/README_EN.md
@@ -29,7 +29,7 @@
## Solutions
-**Solution 1: Bit Manipulation**
+### Solution 1: Bit Manipulation
First, let's consider how to find the first number that is larger than $num$ and has the same number of $1$s in its binary representation.
@@ -45,8 +45,6 @@ The time complexity is $O(\log n)$, where $n$ is the size of $num$. The space co
-### **Python3**
-
```python
class Solution:
def findClosedNumbers(self, num: int) -> List[int]:
@@ -73,8 +71,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
public int[] findClosedNumbers(int num) {
@@ -110,8 +106,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -148,8 +142,6 @@ public:
};
```
-### **Go**
-
```go
func findClosedNumbers(num int) []int {
ans := []int{-1, -1}
@@ -183,8 +175,6 @@ func findClosedNumbers(num int) []int {
}
```
-### **TypeScript**
-
```ts
function findClosedNumbers(num: number): number[] {
const ans: number[] = [-1, -1];
@@ -218,10 +208,6 @@ function findClosedNumbers(num: number): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.06.Convert Integer/README.md b/lcci/05.06.Convert Integer/README.md
index 8acbb8aa3c027..9c14eb779b788 100644
--- a/lcci/05.06.Convert Integer/README.md
+++ b/lcci/05.06.Convert Integer/README.md
@@ -29,9 +29,7 @@
## 解法
-
-
-**方法一:位运算**
+### 方法一:位运算
我们将 A 和 B 进行异或运算,得到的结果中 $1$ 的个数即为需要改变的位数。
@@ -39,10 +37,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def convertInteger(self, A: int, B: int) -> int:
@@ -51,10 +45,6 @@ class Solution:
return (A ^ B).bit_count()
```
-### **Java**
-
-
-
```java
class Solution {
public int convertInteger(int A, int B) {
@@ -63,8 +53,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -75,16 +63,12 @@ public:
};
```
-### **Go**
-
```go
func convertInteger(A int, B int) int {
return bits.OnesCount32(uint32(A ^ B))
}
```
-### **TypeScript**
-
```ts
function convertInteger(A: number, B: number): number {
let res = 0;
@@ -99,8 +83,6 @@ function convertInteger(A: number, B: number): number {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn convert_integer(a: i32, b: i32) -> i32 {
@@ -109,11 +91,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-
-```
-
+
+
diff --git a/lcci/05.06.Convert Integer/README_EN.md b/lcci/05.06.Convert Integer/README_EN.md
index e1b3f8a70d983..b3f47402923d5 100644
--- a/lcci/05.06.Convert Integer/README_EN.md
+++ b/lcci/05.06.Convert Integer/README_EN.md
@@ -46,7 +46,7 @@
## Solutions
-**Solution 1: Bit Manipulation**
+### Solution 1: Bit Manipulation
We perform a bitwise XOR operation on A and B. The number of $1$s in the result is the number of bits that need to be changed.
@@ -54,8 +54,6 @@ The time complexity is $O(\log n)$, where $n$ is the maximum value of A and B. T
-### **Python3**
-
```python
class Solution:
def convertInteger(self, A: int, B: int) -> int:
@@ -64,8 +62,6 @@ class Solution:
return (A ^ B).bit_count()
```
-### **Java**
-
```java
class Solution {
public int convertInteger(int A, int B) {
@@ -74,8 +70,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -86,16 +80,12 @@ public:
};
```
-### **Go**
-
```go
func convertInteger(A int, B int) int {
return bits.OnesCount32(uint32(A ^ B))
}
```
-### **TypeScript**
-
```ts
function convertInteger(A: number, B: number): number {
let res = 0;
@@ -110,8 +100,6 @@ function convertInteger(A: number, B: number): number {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn convert_integer(a: i32, b: i32) -> i32 {
@@ -120,11 +108,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-
-```
-
+
+
diff --git a/lcci/05.07.Exchange/README.md b/lcci/05.07.Exchange/README.md
index ad8bf3a24fa39..3539335ae4dd7 100644
--- a/lcci/05.07.Exchange/README.md
+++ b/lcci/05.07.Exchange/README.md
@@ -29,24 +29,16 @@
## 解法
-
+### 方法一
-### **Python3**
-
-
-
```python
class Solution:
def exchangeBits(self, num: int) -> int:
return ((num & 0x55555555) << 1) | ((num & 0xAAAAAAAA) >> 1)
```
-### **Java**
-
-
-
```java
class Solution {
public int exchangeBits(int num) {
@@ -55,7 +47,20 @@ class Solution {
}
```
-### **Rust**
+```cpp
+class Solution {
+public:
+ int exchangeBits(int num) {
+ return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1;
+ }
+};
+```
+
+```go
+func exchangeBits(num int) int {
+ return ((num & 0x55555555) << 1) | (num&0xaaaaaaaa)>>1
+}
+```
```rust
impl Solution {
@@ -76,29 +81,6 @@ impl Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- int exchangeBits(int num) {
- return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1;
- }
-};
-```
-
-### **Go**
-
-```go
-func exchangeBits(num int) int {
- return ((num & 0x55555555) << 1) | (num&0xaaaaaaaa)>>1
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.07.Exchange/README_EN.md b/lcci/05.07.Exchange/README_EN.md
index 4706724a6f439..ad9d93d17bd10 100644
--- a/lcci/05.07.Exchange/README_EN.md
+++ b/lcci/05.07.Exchange/README_EN.md
@@ -35,9 +35,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -45,8 +45,6 @@ class Solution:
return ((num & 0x55555555) << 1) | ((num & 0xAAAAAAAA) >> 1)
```
-### **Java**
-
```java
class Solution {
public int exchangeBits(int num) {
@@ -55,7 +53,20 @@ class Solution {
}
```
-### **Rust**
+```cpp
+class Solution {
+public:
+ int exchangeBits(int num) {
+ return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1;
+ }
+};
+```
+
+```go
+func exchangeBits(num int) int {
+ return ((num & 0x55555555) << 1) | (num&0xaaaaaaaa)>>1
+}
+```
```rust
impl Solution {
@@ -76,29 +87,6 @@ impl Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- int exchangeBits(int num) {
- return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1;
- }
-};
-```
-
-### **Go**
-
-```go
-func exchangeBits(num int) int {
- return ((num & 0x55555555) << 1) | (num&0xaaaaaaaa)>>1
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/05.08.Draw Line/README.md b/lcci/05.08.Draw Line/README.md
index 44e8010177cd3..9d53be303007d 100644
--- a/lcci/05.08.Draw Line/README.md
+++ b/lcci/05.08.Draw Line/README.md
@@ -19,30 +19,4 @@
## 解法
-
-
-
-
-### **Python3**
-
-
-
-```python
-
-```
-
-### **Java**
-
-
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/05.08.Draw Line/README_EN.md b/lcci/05.08.Draw Line/README_EN.md
index 2848c5016ff6b..4f36bd9d38cc9 100644
--- a/lcci/05.08.Draw Line/README_EN.md
+++ b/lcci/05.08.Draw Line/README_EN.md
@@ -27,24 +27,4 @@
## Solutions
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/08.01.Three Steps Problem/README.md b/lcci/08.01.Three Steps Problem/README.md
index 914d0069b4604..ef79528f40b37 100644
--- a/lcci/08.01.Three Steps Problem/README.md
+++ b/lcci/08.01.Three Steps Problem/README.md
@@ -30,9 +30,7 @@
## 解法
-
-
-**方法一:递推**
+### 方法一:递推
我们定义 $f[i]$ 表示上第 $i$ 阶台阶的方法数,初始时 $f[1]=1$, $f[2]=2$, $f[3]=4$。答案为 $f[n]$。
@@ -42,7 +40,110 @@
时间复杂度 $O(n)$,其中 $n$ 为给定的整数。空间复杂度 $O(1)$。
-**方法二:矩阵快速幂加速递推**
+
+
+```python
+class Solution:
+ def waysToStep(self, n: int) -> int:
+ a, b, c = 1, 2, 4
+ mod = 10**9 + 7
+ for _ in range(n - 1):
+ a, b, c = b, c, (a + b + c) % mod
+ return a
+```
+
+```java
+class Solution {
+ public int waysToStep(int n) {
+ final int mod = (int) 1e9 + 7;
+ int a = 1, b = 2, c = 4;
+ for (int i = 1; i < n; ++i) {
+ int t = a;
+ a = b;
+ b = c;
+ c = (((a + b) % mod) + t) % mod;
+ }
+ return a;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ int waysToStep(int n) {
+ const int mod = 1e9 + 7;
+ int a = 1, b = 2, c = 4;
+ for (int i = 1; i < n; ++i) {
+ int t = a;
+ a = b;
+ b = c;
+ c = (((a + b) % mod) + t) % mod;
+ }
+ return a;
+ }
+};
+```
+
+```go
+func waysToStep(n int) int {
+ const mod int = 1e9 + 7
+ a, b, c := 1, 2, 4
+ for i := 1; i < n; i++ {
+ a, b, c = b, c, (a+b+c)%mod
+ }
+ return a
+}
+```
+
+```rust
+impl Solution {
+ pub fn ways_to_step(n: i32) -> i32 {
+ let (mut a, mut b, mut c) = (1, 2, 4);
+ let m = 1000000007;
+ for _ in 1..n {
+ let t = a;
+ a = b;
+ b = c;
+ c = (((a + b) % m) + t) % m;
+ }
+ a
+ }
+}
+```
+
+```js
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var waysToStep = function (n) {
+ let [a, b, c] = [1, 2, 4];
+ const mod = 1e9 + 7;
+ for (let i = 1; i < n; ++i) {
+ [a, b, c] = [b, c, (a + b + c) % mod];
+ }
+ return a;
+};
+```
+
+```c
+int waysToStep(int n) {
+ const int mod = 1e9 + 7;
+ int a = 1, b = 2, c = 4;
+ for (int i = 1; i < n; ++i) {
+ int t = a;
+ a = b;
+ b = c;
+ c = (((a + b) % mod) + t) % mod;
+ }
+ return a;
+}
+```
+
+
+
+### 方法二:矩阵快速幂加速递推
我们设 $F(n)$ 表示一个 $1 \times 3$ 的矩阵 $\begin{bmatrix} F_{n - 1} & F_{n - 2} & F_{n - 3} \end{bmatrix}$,其中 $F_{n - 1}$, $F_{n - 2}$ 和 $F_{n - 3}$ 分别表示上第 $n - 1$ 阶、第 $n - 2$ 阶和第 $n - 3$ 阶台阶的方法数。
@@ -70,20 +171,6 @@ $$
-### **Python3**
-
-
-
-```python
-class Solution:
- def waysToStep(self, n: int) -> int:
- a, b, c = 1, 2, 4
- mod = 10**9 + 7
- for _ in range(n - 1):
- a, b, c = b, c, (a + b + c) % mod
- return a
-```
-
```python
class Solution:
def waysToStep(self, n: int) -> int:
@@ -113,46 +200,6 @@ class Solution:
return sum(pow(a, n - 4)[0]) % mod
```
-```python
-import numpy as np
-
-
-class Solution:
- def waysToStep(self, n: int) -> int:
- if n < 4:
- return 2 ** (n - 1)
- mod = 10**9 + 7
- factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O"))
- res = np.mat([(4, 2, 1)], np.dtype("O"))
- n -= 4
- while n:
- if n & 1:
- res = res * factor % mod
- factor = factor * factor % mod
- n >>= 1
- return res.sum() % mod
-```
-
-### **Java**
-
-
-
-```java
-class Solution {
- public int waysToStep(int n) {
- final int mod = (int) 1e9 + 7;
- int a = 1, b = 2, c = 4;
- for (int i = 1; i < n; ++i) {
- int t = a;
- a = b;
- b = c;
- c = (((a + b) % mod) + t) % mod;
- }
- return a;
- }
-}
-```
-
```java
class Solution {
private final int mod = (int) 1e9 + 7;
@@ -197,25 +244,6 @@ class Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- int waysToStep(int n) {
- const int mod = 1e9 + 7;
- int a = 1, b = 2, c = 4;
- for (int i = 1; i < n; ++i) {
- int t = a;
- a = b;
- b = c;
- c = (((a + b) % mod) + t) % mod;
- }
- return a;
- }
-};
-```
-
```cpp
class Solution {
public:
@@ -262,19 +290,6 @@ private:
};
```
-### **Go**
-
-```go
-func waysToStep(n int) int {
- const mod int = 1e9 + 7
- a, b, c := 1, 2, 4
- for i := 1; i < n; i++ {
- a, b, c = b, c, (a+b+c)%mod
- }
- return a
-}
-```
-
```go
const mod = 1e9 + 7
@@ -319,23 +334,6 @@ func pow(a [][]int, n int) [][]int {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number} n
- * @return {number}
- */
-var waysToStep = function (n) {
- let [a, b, c] = [1, 2, 4];
- const mod = 1e9 + 7;
- for (let i = 1; i < n; ++i) {
- [a, b, c] = [b, c, (a + b + c) % mod];
- }
- return a;
-};
-```
-
```js
/**
* @param {number} n
@@ -388,38 +386,32 @@ function pow(a, n) {
}
```
-### **C**
+
-```c
-int waysToStep(int n) {
- const int mod = 1e9 + 7;
- int a = 1, b = 2, c = 4;
- for (int i = 1; i < n; ++i) {
- int t = a;
- a = b;
- b = c;
- c = (((a + b) % mod) + t) % mod;
- }
- return a;
-}
-```
+### 方法三
-### **Rust**
+
-```rust
-impl Solution {
- pub fn ways_to_step(n: i32) -> i32 {
- let (mut a, mut b, mut c) = (1, 2, 4);
- let m = 1000000007;
- for _ in 1..n {
- let t = a;
- a = b;
- b = c;
- c = (((a + b) % m) + t) % m;
- }
- a
- }
-}
+```python
+import numpy as np
+
+
+class Solution:
+ def waysToStep(self, n: int) -> int:
+ if n < 4:
+ return 2 ** (n - 1)
+ mod = 10**9 + 7
+ factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O"))
+ res = np.mat([(4, 2, 1)], np.dtype("O"))
+ n -= 4
+ while n:
+ if n & 1:
+ res = res * factor % mod
+ factor = factor * factor % mod
+ n >>= 1
+ return res.sum() % mod
```
+
+
diff --git a/lcci/08.01.Three Steps Problem/README_EN.md b/lcci/08.01.Three Steps Problem/README_EN.md
index 8d26883778df9..fbd07e6ed265c 100644
--- a/lcci/08.01.Three Steps Problem/README_EN.md
+++ b/lcci/08.01.Three Steps Problem/README_EN.md
@@ -32,7 +32,7 @@
## Solutions
-**Solution 1: Recursion**
+### Solution 1: Recursion
We define $f[i]$ as the number of ways to reach the $i$-th step, initially $f[1]=1$, $f[2]=2$, $f[3]=4$. The answer is $f[n]$.
@@ -42,7 +42,110 @@ Since $f[i]$ is only related to $f[i-1]$, $f[i-2]$, $f[i-3]$, we can use three v
The time complexity is $O(n)$, where $n$ is the given integer. The space complexity is $O(1)$.
-**Solution 2: Matrix Quick Power to Accelerate Recursion**
+
+
+```python
+class Solution:
+ def waysToStep(self, n: int) -> int:
+ a, b, c = 1, 2, 4
+ mod = 10**9 + 7
+ for _ in range(n - 1):
+ a, b, c = b, c, (a + b + c) % mod
+ return a
+```
+
+```java
+class Solution {
+ public int waysToStep(int n) {
+ final int mod = (int) 1e9 + 7;
+ int a = 1, b = 2, c = 4;
+ for (int i = 1; i < n; ++i) {
+ int t = a;
+ a = b;
+ b = c;
+ c = (((a + b) % mod) + t) % mod;
+ }
+ return a;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ int waysToStep(int n) {
+ const int mod = 1e9 + 7;
+ int a = 1, b = 2, c = 4;
+ for (int i = 1; i < n; ++i) {
+ int t = a;
+ a = b;
+ b = c;
+ c = (((a + b) % mod) + t) % mod;
+ }
+ return a;
+ }
+};
+```
+
+```go
+func waysToStep(n int) int {
+ const mod int = 1e9 + 7
+ a, b, c := 1, 2, 4
+ for i := 1; i < n; i++ {
+ a, b, c = b, c, (a+b+c)%mod
+ }
+ return a
+}
+```
+
+```rust
+impl Solution {
+ pub fn ways_to_step(n: i32) -> i32 {
+ let (mut a, mut b, mut c) = (1, 2, 4);
+ let m = 1000000007;
+ for _ in 1..n {
+ let t = a;
+ a = b;
+ b = c;
+ c = (((a + b) % m) + t) % m;
+ }
+ a
+ }
+}
+```
+
+```js
+/**
+ * @param {number} n
+ * @return {number}
+ */
+var waysToStep = function (n) {
+ let [a, b, c] = [1, 2, 4];
+ const mod = 1e9 + 7;
+ for (let i = 1; i < n; ++i) {
+ [a, b, c] = [b, c, (a + b + c) % mod];
+ }
+ return a;
+};
+```
+
+```c
+int waysToStep(int n) {
+ const int mod = 1e9 + 7;
+ int a = 1, b = 2, c = 4;
+ for (int i = 1; i < n; ++i) {
+ int t = a;
+ a = b;
+ b = c;
+ c = (((a + b) % mod) + t) % mod;
+ }
+ return a;
+}
+```
+
+
+
+### Solution 2: Matrix Quick Power to Accelerate Recursion
We set $F(n)$ to represent a $1 \times 3$ matrix $\begin{bmatrix} F_{n - 1} & F_{n - 2} & F_{n - 3} \end{bmatrix}$, where $F_{n - 1}$, $F_{n - 2}$ and $F_{n - 3}$ respectively represent the number of ways to reach the $n - 1$-th, $n - 2$-th and $n - 3$-th steps.
@@ -70,18 +173,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$.
-### **Python3**
-
-```python
-class Solution:
- def waysToStep(self, n: int) -> int:
- a, b, c = 1, 2, 4
- mod = 10**9 + 7
- for _ in range(n - 1):
- a, b, c = b, c, (a + b + c) % mod
- return a
-```
-
```python
class Solution:
def waysToStep(self, n: int) -> int:
@@ -111,44 +202,6 @@ class Solution:
return sum(pow(a, n - 4)[0]) % mod
```
-```python
-import numpy as np
-
-
-class Solution:
- def waysToStep(self, n: int) -> int:
- if n < 4:
- return 2 ** (n - 1)
- mod = 10**9 + 7
- factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O"))
- res = np.mat([(4, 2, 1)], np.dtype("O"))
- n -= 4
- while n:
- if n & 1:
- res = res * factor % mod
- factor = factor * factor % mod
- n >>= 1
- return res.sum() % mod
-```
-
-### **Java**
-
-```java
-class Solution {
- public int waysToStep(int n) {
- final int mod = (int) 1e9 + 7;
- int a = 1, b = 2, c = 4;
- for (int i = 1; i < n; ++i) {
- int t = a;
- a = b;
- b = c;
- c = (((a + b) % mod) + t) % mod;
- }
- return a;
- }
-}
-```
-
```java
class Solution {
private final int mod = (int) 1e9 + 7;
@@ -193,25 +246,6 @@ class Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- int waysToStep(int n) {
- const int mod = 1e9 + 7;
- int a = 1, b = 2, c = 4;
- for (int i = 1; i < n; ++i) {
- int t = a;
- a = b;
- b = c;
- c = (((a + b) % mod) + t) % mod;
- }
- return a;
- }
-};
-```
-
```cpp
class Solution {
public:
@@ -258,19 +292,6 @@ private:
};
```
-### **Go**
-
-```go
-func waysToStep(n int) int {
- const mod int = 1e9 + 7
- a, b, c := 1, 2, 4
- for i := 1; i < n; i++ {
- a, b, c = b, c, (a+b+c)%mod
- }
- return a
-}
-```
-
```go
const mod = 1e9 + 7
@@ -315,23 +336,6 @@ func pow(a [][]int, n int) [][]int {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number} n
- * @return {number}
- */
-var waysToStep = function (n) {
- let [a, b, c] = [1, 2, 4];
- const mod = 1e9 + 7;
- for (let i = 1; i < n; ++i) {
- [a, b, c] = [b, c, (a + b + c) % mod];
- }
- return a;
-};
-```
-
```js
/**
* @param {number} n
@@ -384,38 +388,32 @@ function pow(a, n) {
}
```
-### **C**
+
-```c
-int waysToStep(int n) {
- const int mod = 1e9 + 7;
- int a = 1, b = 2, c = 4;
- for (int i = 1; i < n; ++i) {
- int t = a;
- a = b;
- b = c;
- c = (((a + b) % mod) + t) % mod;
- }
- return a;
-}
-```
+### Solution 3
-### **Rust**
+
-```rust
-impl Solution {
- pub fn ways_to_step(n: i32) -> i32 {
- let (mut a, mut b, mut c) = (1, 2, 4);
- let m = 1000000007;
- for _ in 1..n {
- let t = a;
- a = b;
- b = c;
- c = (((a + b) % m) + t) % m;
- }
- a
- }
-}
+```python
+import numpy as np
+
+
+class Solution:
+ def waysToStep(self, n: int) -> int:
+ if n < 4:
+ return 2 ** (n - 1)
+ mod = 10**9 + 7
+ factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O"))
+ res = np.mat([(4, 2, 1)], np.dtype("O"))
+ n -= 4
+ while n:
+ if n & 1:
+ res = res * factor % mod
+ factor = factor * factor % mod
+ n >>= 1
+ return res.sum() % mod
```
+
+
diff --git a/lcci/08.02.Robot in a Grid/README.md b/lcci/08.02.Robot in a Grid/README.md
index 0adb67854d256..81673434d8418 100644
--- a/lcci/08.02.Robot in a Grid/README.md
+++ b/lcci/08.02.Robot in a Grid/README.md
@@ -24,9 +24,7 @@
## 解法
-
-
-**方法一:DFS**
+### 方法一:DFS
我们可以使用深度优先搜索来解决本题。我们从左上角开始,向右或向下移动,直到到达右下角。如果在某一步,我们发现当前位置是障碍物,或者当前位置已经在路径中,那么我们就返回,否则我们将当前位置加入路径中,并且标记当前位置为已经访问过,然后继续向右或向下移动。
@@ -36,10 +34,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def pathWithObstacles(self, obstacleGrid: List[List[int]]) -> List[List[int]]:
@@ -58,10 +52,6 @@ class Solution:
return ans if dfs(0, 0) else []
```
-### **Java**
-
-
-
```java
class Solution {
private List> ans = new ArrayList<>();
@@ -91,8 +81,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -117,8 +105,6 @@ public:
};
```
-### **Go**
-
```go
func pathWithObstacles(obstacleGrid [][]int) [][]int {
m, n := len(obstacleGrid), len(obstacleGrid[0])
@@ -143,8 +129,6 @@ func pathWithObstacles(obstacleGrid [][]int) [][]int {
}
```
-### **TypeScript**
-
```ts
function pathWithObstacles(obstacleGrid: number[][]): number[][] {
const m = obstacleGrid.length;
@@ -169,8 +153,6 @@ function pathWithObstacles(obstacleGrid: number[][]): number[][] {
}
```
-### **Rust**
-
```rust
impl Solution {
fn dfs(grid: &mut Vec>, path: &mut Vec>, i: usize, j: usize) -> bool {
@@ -200,10 +182,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.02.Robot in a Grid/README_EN.md b/lcci/08.02.Robot in a Grid/README_EN.md
index 652e29c11defe..ceaac32445caa 100644
--- a/lcci/08.02.Robot in a Grid/README_EN.md
+++ b/lcci/08.02.Robot in a Grid/README_EN.md
@@ -32,7 +32,7 @@
## Solutions
-**Solution 1: DFS (Depth-First Search)**
+### Solution 1: DFS (Depth-First Search)
We can use depth-first search to solve this problem. We start from the top left corner and move right or down until we reach the bottom right corner. If at some step, we find that the current position is an obstacle, or the current position is already in the path, then we return. Otherwise, we add the current position to the path and mark the current position as visited, then continue to move right or down.
@@ -42,8 +42,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times
-### **Python3**
-
```python
class Solution:
def pathWithObstacles(self, obstacleGrid: List[List[int]]) -> List[List[int]]:
@@ -62,8 +60,6 @@ class Solution:
return ans if dfs(0, 0) else []
```
-### **Java**
-
```java
class Solution {
private List> ans = new ArrayList<>();
@@ -93,8 +89,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -119,8 +113,6 @@ public:
};
```
-### **Go**
-
```go
func pathWithObstacles(obstacleGrid [][]int) [][]int {
m, n := len(obstacleGrid), len(obstacleGrid[0])
@@ -145,8 +137,6 @@ func pathWithObstacles(obstacleGrid [][]int) [][]int {
}
```
-### **TypeScript**
-
```ts
function pathWithObstacles(obstacleGrid: number[][]): number[][] {
const m = obstacleGrid.length;
@@ -171,8 +161,6 @@ function pathWithObstacles(obstacleGrid: number[][]): number[][] {
}
```
-### **Rust**
-
```rust
impl Solution {
fn dfs(grid: &mut Vec>, path: &mut Vec>, i: usize, j: usize) -> bool {
@@ -202,10 +190,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.03.Magic Index/README.md b/lcci/08.03.Magic Index/README.md
index 76f01adf62756..69924ac5de815 100644
--- a/lcci/08.03.Magic Index/README.md
+++ b/lcci/08.03.Magic Index/README.md
@@ -28,28 +28,10 @@
## 解法
-
-
-**线性查找:**
-
-遍历数组,当 `A[i] = i` 时直接返回即可。
-
-**优化:**
-
-在遍历的基础,进行可能的 "跳跃",结束时执行 `i = max(A[i], i + 1)`,而不再单纯 `i++`。
-
-可行性证明:
-
-因为数组是**有序**的,若 `A[i] != i`,那么就可以将 `A[i]` 以下的可能全部排除,直接将 `i` 设定为 `A[i]`。
-
-若是考虑最糟的状况(所有元素都为负数),则该优化与遍历无差别。
+### 方法一
-### **Python3**
-
-
-
```python
class Solution:
def findMagicIndex(self, nums: List[int]) -> int:
@@ -67,10 +49,6 @@ class Solution:
return find(nums, 0, len(nums) - 1)
```
-### **Java**
-
-
-
```java
class Solution {
public int findMagicIndex(int[] nums) {
@@ -95,29 +73,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var findMagicIndex = function (nums) {
- return helper(nums, 0, nums.length - 1);
-};
-
-function helper(nums, left, right) {
- if (left > right) return -1;
- let mid = Math.floor((left + right) / 2);
- let leftIndex = helper(nums, left, mid - 1);
- if (leftIndex != -1) return leftIndex;
- if (nums[mid] == mid) return mid;
- return helper(nums, mid + 1, right);
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -142,8 +97,6 @@ public:
};
```
-### **Go**
-
```go
func findMagicIndex(nums []int) int {
return find(nums, 0, len(nums)-1)
@@ -165,8 +118,6 @@ func find(nums []int, left, right int) int {
}
```
-### **TypeScript**
-
```ts
function findMagicIndex(nums: number[]): number {
const n = nums.length;
@@ -190,22 +141,6 @@ function findMagicIndex(nums: number[]): number {
}
```
-```ts
-function findMagicIndex(nums: number[]): number {
- const n = nums.length;
- let i = 0;
- while (i < n) {
- if (nums[i] === i) {
- return i;
- }
- i = Math.max(nums[i], i + 1);
- }
- return -1;
-}
-```
-
-## **Rust**
-
```rust
impl Solution {
fn find(nums: &Vec, l: usize, r: usize) -> i32 {
@@ -231,6 +166,45 @@ impl Solution {
}
```
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var findMagicIndex = function (nums) {
+ return helper(nums, 0, nums.length - 1);
+};
+
+function helper(nums, left, right) {
+ if (left > right) return -1;
+ let mid = Math.floor((left + right) / 2);
+ let leftIndex = helper(nums, left, mid - 1);
+ if (leftIndex != -1) return leftIndex;
+ if (nums[mid] == mid) return mid;
+ return helper(nums, mid + 1, right);
+}
+```
+
+
+
+### 方法二
+
+
+
+```ts
+function findMagicIndex(nums: number[]): number {
+ const n = nums.length;
+ let i = 0;
+ while (i < n) {
+ if (nums[i] === i) {
+ return i;
+ }
+ i = Math.max(nums[i], i + 1);
+ }
+ return -1;
+}
+```
+
```rust
impl Solution {
pub fn find_magic_index(nums: Vec) -> i32 {
@@ -248,10 +222,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.03.Magic Index/README_EN.md b/lcci/08.03.Magic Index/README_EN.md
index a47b9e35baebe..e303eff8fa259 100644
--- a/lcci/08.03.Magic Index/README_EN.md
+++ b/lcci/08.03.Magic Index/README_EN.md
@@ -34,9 +34,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -55,8 +55,6 @@ class Solution:
return find(nums, 0, len(nums) - 1)
```
-### **Java**
-
```java
class Solution {
public int findMagicIndex(int[] nums) {
@@ -81,29 +79,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var findMagicIndex = function (nums) {
- return helper(nums, 0, nums.length - 1);
-};
-
-function helper(nums, left, right) {
- if (left > right) return -1;
- let mid = Math.floor((left + right) / 2);
- let leftIndex = helper(nums, left, mid - 1);
- if (leftIndex != -1) return leftIndex;
- if (nums[mid] == mid) return mid;
- return helper(nums, mid + 1, right);
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -128,8 +103,6 @@ public:
};
```
-### **Go**
-
```go
func findMagicIndex(nums []int) int {
return find(nums, 0, len(nums)-1)
@@ -151,8 +124,6 @@ func find(nums []int, left, right int) int {
}
```
-### **TypeScript**
-
```ts
function findMagicIndex(nums: number[]): number {
const n = nums.length;
@@ -176,22 +147,6 @@ function findMagicIndex(nums: number[]): number {
}
```
-```ts
-function findMagicIndex(nums: number[]): number {
- const n = nums.length;
- let i = 0;
- while (i < n) {
- if (nums[i] === i) {
- return i;
- }
- i = Math.max(nums[i], i + 1);
- }
- return -1;
-}
-```
-
-## **Rust**
-
```rust
impl Solution {
fn find(nums: &Vec, l: usize, r: usize) -> i32 {
@@ -217,6 +172,45 @@ impl Solution {
}
```
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var findMagicIndex = function (nums) {
+ return helper(nums, 0, nums.length - 1);
+};
+
+function helper(nums, left, right) {
+ if (left > right) return -1;
+ let mid = Math.floor((left + right) / 2);
+ let leftIndex = helper(nums, left, mid - 1);
+ if (leftIndex != -1) return leftIndex;
+ if (nums[mid] == mid) return mid;
+ return helper(nums, mid + 1, right);
+}
+```
+
+
+
+### Solution 2
+
+
+
+```ts
+function findMagicIndex(nums: number[]): number {
+ const n = nums.length;
+ let i = 0;
+ while (i < n) {
+ if (nums[i] === i) {
+ return i;
+ }
+ i = Math.max(nums[i], i + 1);
+ }
+ return -1;
+}
+```
+
```rust
impl Solution {
pub fn find_magic_index(nums: Vec) -> i32 {
@@ -234,10 +228,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.04.Power Set/README.md b/lcci/08.04.Power Set/README.md
index 62052a908c4f6..9e6971d61f690 100644
--- a/lcci/08.04.Power Set/README.md
+++ b/lcci/08.04.Power Set/README.md
@@ -27,9 +27,7 @@
## 解法
-
-
-**方法一:递归枚举**
+### 方法一:递归枚举
我们设计一个递归函数 $dfs(u, t)$,它的参数为当前枚举到的元素的下标 $u$,以及当前的子集 $t$。
@@ -37,20 +35,8 @@
时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。数组中每个元素有两种状态,即选择或不选择,共 $2^n$ 种状态,每种状态需要 $O(n)$ 的时间来构造子集。
-**方法二:二进制枚举**
-
-我们可以将方法一中的递归过程改写成迭代的形式,即使用二进制枚举的方法来枚举所有的子集。
-
-我们可以使用 $2^n$ 个二进制数来表示 $n$ 个元素的所有子集,若某个二进制数 `mask` 的第 $i$ 位为 $1$,表示子集中包含数组第 $i$ 个元素 $v$;若为 $0$,表示子集中不包含数组第 $i$ 个元素 $v$。
-
-时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。一共有 $2^n$ 个子集,每个子集需要 $O(n)$ 的时间来构造。
-
-### **Python3**
-
-
-
```python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
@@ -68,23 +54,6 @@ class Solution:
return ans
```
-```python
-class Solution:
- def subsets(self, nums: List[int]) -> List[List[int]]:
- ans = []
- for mask in range(1 << len(nums)):
- t = []
- for i, v in enumerate(nums):
- if (mask >> i) & 1:
- t.append(v)
- ans.append(t)
- return ans
-```
-
-### **Java**
-
-
-
```java
class Solution {
private List> ans = new ArrayList<>();
@@ -109,27 +78,6 @@ class Solution {
}
```
-```java
-class Solution {
- public List> subsets(int[] nums) {
- int n = nums.length;
- List> ans = new ArrayList<>();
- for (int mask = 0; mask < 1 << n; ++mask) {
- List t = new ArrayList<>();
- for (int i = 0; i < n; ++i) {
- if (((mask >> i) & 1) == 1) {
- t.add(nums[i]);
- }
- }
- ans.add(t);
- }
- return ans;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -153,6 +101,120 @@ public:
};
```
+```go
+func subsets(nums []int) [][]int {
+ var ans [][]int
+ var dfs func(u int, t []int)
+ dfs = func(u int, t []int) {
+ if u == len(nums) {
+ ans = append(ans, append([]int(nil), t...))
+ return
+ }
+ dfs(u+1, t)
+ t = append(t, nums[u])
+ dfs(u+1, t)
+ t = t[:len(t)-1]
+ }
+ var t []int
+ dfs(0, t)
+ return ans
+}
+```
+
+```ts
+function subsets(nums: number[]): number[][] {
+ const res = [[]];
+ nums.forEach(num => {
+ res.forEach(item => {
+ res.push(item.concat(num));
+ });
+ });
+ return res;
+}
+```
+
+```rust
+impl Solution {
+ pub fn subsets(nums: Vec) -> Vec> {
+ let n = nums.len();
+ let mut res: Vec> = vec![vec![]];
+ for i in 0..n {
+ for j in 0..res.len() {
+ res.push(vec![..res[j].clone(), vec![nums[i]]].concat());
+ }
+ }
+ res
+ }
+}
+```
+
+```js
+/**
+ * @param {number[]} nums
+ * @return {number[][]}
+ */
+var subsets = function (nums) {
+ let prev = [];
+ let res = [];
+ dfs(nums, 0, prev, res);
+ return res;
+};
+
+function dfs(nums, depth, prev, res) {
+ res.push(prev.slice());
+ for (let i = depth; i < nums.length; i++) {
+ prev.push(nums[i]);
+ depth++;
+ dfs(nums, depth, prev, res);
+ prev.pop();
+ }
+}
+```
+
+
+
+### 方法二:二进制枚举
+
+我们可以将方法一中的递归过程改写成迭代的形式,即使用二进制枚举的方法来枚举所有的子集。
+
+我们可以使用 $2^n$ 个二进制数来表示 $n$ 个元素的所有子集,若某个二进制数 `mask` 的第 $i$ 位为 $1$,表示子集中包含数组第 $i$ 个元素 $v$;若为 $0$,表示子集中不包含数组第 $i$ 个元素 $v$。
+
+时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。一共有 $2^n$ 个子集,每个子集需要 $O(n)$ 的时间来构造。
+
+
+
+```python
+class Solution:
+ def subsets(self, nums: List[int]) -> List[List[int]]:
+ ans = []
+ for mask in range(1 << len(nums)):
+ t = []
+ for i, v in enumerate(nums):
+ if (mask >> i) & 1:
+ t.append(v)
+ ans.append(t)
+ return ans
+```
+
+```java
+class Solution {
+ public List> subsets(int[] nums) {
+ int n = nums.length;
+ List> ans = new ArrayList<>();
+ for (int mask = 0; mask < 1 << n; ++mask) {
+ List t = new ArrayList<>();
+ for (int i = 0; i < n; ++i) {
+ if (((mask >> i) & 1) == 1) {
+ t.add(nums[i]);
+ }
+ }
+ ans.add(t);
+ }
+ return ans;
+ }
+}
+```
+
```cpp
class Solution {
public:
@@ -174,28 +236,6 @@ public:
};
```
-### **Go**
-
-```go
-func subsets(nums []int) [][]int {
- var ans [][]int
- var dfs func(u int, t []int)
- dfs = func(u int, t []int) {
- if u == len(nums) {
- ans = append(ans, append([]int(nil), t...))
- return
- }
- dfs(u+1, t)
- t = append(t, nums[u])
- dfs(u+1, t)
- t = t[:len(t)-1]
- }
- var t []int
- dfs(0, t)
- return ans
-}
-```
-
```go
func subsets(nums []int) [][]int {
var ans [][]int
@@ -213,20 +253,6 @@ func subsets(nums []int) [][]int {
}
```
-### **TypeScript**
-
-```ts
-function subsets(nums: number[]): number[][] {
- const res = [[]];
- nums.forEach(num => {
- res.forEach(item => {
- res.push(item.concat(num));
- });
- });
- return res;
-}
-```
-
```ts
function subsets(nums: number[]): number[][] {
const n = nums.length;
@@ -247,23 +273,6 @@ function subsets(nums: number[]): number[][] {
}
```
-### **Rust**
-
-```rust
-impl Solution {
- pub fn subsets(nums: Vec) -> Vec> {
- let n = nums.len();
- let mut res: Vec> = vec![vec![]];
- for i in 0..n {
- for j in 0..res.len() {
- res.push(vec![..res[j].clone(), vec![nums[i]]].concat());
- }
- }
- res
- }
-}
-```
-
```rust
impl Solution {
fn dfs(nums: &Vec, i: usize, res: &mut Vec>, list: &mut Vec) {
@@ -285,10 +294,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.04.Power Set/README_EN.md b/lcci/08.04.Power Set/README_EN.md
index 03dbdf4f8ad85..1e361e61be8ba 100644
--- a/lcci/08.04.Power Set/README_EN.md
+++ b/lcci/08.04.Power Set/README_EN.md
@@ -40,7 +40,7 @@
## Solutions
-**Solution 1: Recursive Enumeration**
+### Solution 1: Recursive Enumeration
We design a recursive function $dfs(u, t)$, where $u$ is the index of the current element being enumerated, and $t$ is the current subset.
@@ -48,18 +48,8 @@ For the current element with index $u$, we can choose to add it to the subset $t
The time complexity is $O(n \times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. Each element in the array has two states, namely chosen or not chosen, for a total of $2^n$ states. Each state requires $O(n)$ time to construct the subset.
-**Solution 2: Binary Enumeration**
-
-We can rewrite the recursive process in Method 1 into an iterative form, that is, using binary enumeration to enumerate all subsets.
-
-We can use $2^n$ binary numbers to represent all subsets of $n$ elements. If the $i$-th bit of a binary number `mask` is $1$, it means that the subset contains the $i$-th element $v$ of the array; if it is $0$, it means that the subset does not contain the $i$-th element $v$ of the array.
-
-The time complexity is $O(n \times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. There are a total of $2^n$ subsets, and each subset requires $O(n)$ time to construct.
-
-### **Python3**
-
```python
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
@@ -77,21 +67,6 @@ class Solution:
return ans
```
-```python
-class Solution:
- def subsets(self, nums: List[int]) -> List[List[int]]:
- ans = []
- for mask in range(1 << len(nums)):
- t = []
- for i, v in enumerate(nums):
- if (mask >> i) & 1:
- t.append(v)
- ans.append(t)
- return ans
-```
-
-### **Java**
-
```java
class Solution {
private List> ans = new ArrayList<>();
@@ -116,27 +91,6 @@ class Solution {
}
```
-```java
-class Solution {
- public List> subsets(int[] nums) {
- int n = nums.length;
- List> ans = new ArrayList<>();
- for (int mask = 0; mask < 1 << n; ++mask) {
- List t = new ArrayList<>();
- for (int i = 0; i < n; ++i) {
- if (((mask >> i) & 1) == 1) {
- t.add(nums[i]);
- }
- }
- ans.add(t);
- }
- return ans;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -160,6 +114,120 @@ public:
};
```
+```go
+func subsets(nums []int) [][]int {
+ var ans [][]int
+ var dfs func(u int, t []int)
+ dfs = func(u int, t []int) {
+ if u == len(nums) {
+ ans = append(ans, append([]int(nil), t...))
+ return
+ }
+ dfs(u+1, t)
+ t = append(t, nums[u])
+ dfs(u+1, t)
+ t = t[:len(t)-1]
+ }
+ var t []int
+ dfs(0, t)
+ return ans
+}
+```
+
+```ts
+function subsets(nums: number[]): number[][] {
+ const res = [[]];
+ nums.forEach(num => {
+ res.forEach(item => {
+ res.push(item.concat(num));
+ });
+ });
+ return res;
+}
+```
+
+```rust
+impl Solution {
+ pub fn subsets(nums: Vec) -> Vec> {
+ let n = nums.len();
+ let mut res: Vec> = vec![vec![]];
+ for i in 0..n {
+ for j in 0..res.len() {
+ res.push(vec![..res[j].clone(), vec![nums[i]]].concat());
+ }
+ }
+ res
+ }
+}
+```
+
+```js
+/**
+ * @param {number[]} nums
+ * @return {number[][]}
+ */
+var subsets = function (nums) {
+ let prev = [];
+ let res = [];
+ dfs(nums, 0, prev, res);
+ return res;
+};
+
+function dfs(nums, depth, prev, res) {
+ res.push(prev.slice());
+ for (let i = depth; i < nums.length; i++) {
+ prev.push(nums[i]);
+ depth++;
+ dfs(nums, depth, prev, res);
+ prev.pop();
+ }
+}
+```
+
+
+
+### Solution 2: Binary Enumeration
+
+We can rewrite the recursive process in Method 1 into an iterative form, that is, using binary enumeration to enumerate all subsets.
+
+We can use $2^n$ binary numbers to represent all subsets of $n$ elements. If the $i$-th bit of a binary number `mask` is $1$, it means that the subset contains the $i$-th element $v$ of the array; if it is $0$, it means that the subset does not contain the $i$-th element $v$ of the array.
+
+The time complexity is $O(n \times 2^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. There are a total of $2^n$ subsets, and each subset requires $O(n)$ time to construct.
+
+
+
+```python
+class Solution:
+ def subsets(self, nums: List[int]) -> List[List[int]]:
+ ans = []
+ for mask in range(1 << len(nums)):
+ t = []
+ for i, v in enumerate(nums):
+ if (mask >> i) & 1:
+ t.append(v)
+ ans.append(t)
+ return ans
+```
+
+```java
+class Solution {
+ public List> subsets(int[] nums) {
+ int n = nums.length;
+ List> ans = new ArrayList<>();
+ for (int mask = 0; mask < 1 << n; ++mask) {
+ List t = new ArrayList<>();
+ for (int i = 0; i < n; ++i) {
+ if (((mask >> i) & 1) == 1) {
+ t.add(nums[i]);
+ }
+ }
+ ans.add(t);
+ }
+ return ans;
+ }
+}
+```
+
```cpp
class Solution {
public:
@@ -181,28 +249,6 @@ public:
};
```
-### **Go**
-
-```go
-func subsets(nums []int) [][]int {
- var ans [][]int
- var dfs func(u int, t []int)
- dfs = func(u int, t []int) {
- if u == len(nums) {
- ans = append(ans, append([]int(nil), t...))
- return
- }
- dfs(u+1, t)
- t = append(t, nums[u])
- dfs(u+1, t)
- t = t[:len(t)-1]
- }
- var t []int
- dfs(0, t)
- return ans
-}
-```
-
```go
func subsets(nums []int) [][]int {
var ans [][]int
@@ -220,20 +266,6 @@ func subsets(nums []int) [][]int {
}
```
-### **TypeScript**
-
-```ts
-function subsets(nums: number[]): number[][] {
- const res = [[]];
- nums.forEach(num => {
- res.forEach(item => {
- res.push(item.concat(num));
- });
- });
- return res;
-}
-```
-
```ts
function subsets(nums: number[]): number[][] {
const n = nums.length;
@@ -254,23 +286,6 @@ function subsets(nums: number[]): number[][] {
}
```
-### **Rust**
-
-```rust
-impl Solution {
- pub fn subsets(nums: Vec) -> Vec> {
- let n = nums.len();
- let mut res: Vec> = vec![vec![]];
- for i in 0..n {
- for j in 0..res.len() {
- res.push(vec![..res[j].clone(), vec![nums[i]]].concat());
- }
- }
- res
- }
-}
-```
-
```rust
impl Solution {
fn dfs(nums: &Vec, i: usize, res: &mut Vec>, list: &mut Vec) {
@@ -292,10 +307,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.05.Recursive Mulitply/README.md b/lcci/08.05.Recursive Mulitply/README.md
index 0d9d81c58a3b2..3971033ab0405 100644
--- a/lcci/08.05.Recursive Mulitply/README.md
+++ b/lcci/08.05.Recursive Mulitply/README.md
@@ -23,9 +23,7 @@
## 解法
-
-
-**方法一:递归 + 位运算**
+### 方法一:递归 + 位运算
我们先判断 $B$ 是否为 $1$,如果是,那么直接返回 $A$。
@@ -35,10 +33,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def multiply(self, A: int, B: int) -> int:
@@ -49,10 +43,6 @@ class Solution:
return self.multiply(A, B >> 1) << 1
```
-### **Java**
-
-
-
```java
class Solution {
public int multiply(int A, int B) {
@@ -67,8 +57,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -84,8 +72,6 @@ public:
};
```
-### **Go**
-
```go
func multiply(A int, B int) int {
if B == 1 {
@@ -98,8 +84,6 @@ func multiply(A int, B int) int {
}
```
-### **TypeScript**
-
```ts
function multiply(A: number, B: number): number {
if (B === 1) {
@@ -112,8 +96,6 @@ function multiply(A: number, B: number): number {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn multiply(a: i32, b: i32) -> i32 {
@@ -128,10 +110,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.05.Recursive Mulitply/README_EN.md b/lcci/08.05.Recursive Mulitply/README_EN.md
index 9e8a17c683282..2a3bc5759ad10 100644
--- a/lcci/08.05.Recursive Mulitply/README_EN.md
+++ b/lcci/08.05.Recursive Mulitply/README_EN.md
@@ -28,7 +28,7 @@
## Solutions
-**Solution 1: Recursion + Bit Manipulation**
+### Solution 1: Recursion + Bit Manipulation
First, we check if $B$ is $1$. If it is, we directly return $A$.
@@ -38,8 +38,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Her
-### **Python3**
-
```python
class Solution:
def multiply(self, A: int, B: int) -> int:
@@ -50,8 +48,6 @@ class Solution:
return self.multiply(A, B >> 1) << 1
```
-### **Java**
-
```java
class Solution {
public int multiply(int A, int B) {
@@ -66,8 +62,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -83,8 +77,6 @@ public:
};
```
-### **Go**
-
```go
func multiply(A int, B int) int {
if B == 1 {
@@ -97,8 +89,6 @@ func multiply(A int, B int) int {
}
```
-### **TypeScript**
-
```ts
function multiply(A: number, B: number): number {
if (B === 1) {
@@ -111,8 +101,6 @@ function multiply(A: number, B: number): number {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn multiply(a: i32, b: i32) -> i32 {
@@ -127,10 +115,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.06.Hanota/README.md b/lcci/08.06.Hanota/README.md
index 49321b3f1a0d7..869b8c05a57be 100644
--- a/lcci/08.06.Hanota/README.md
+++ b/lcci/08.06.Hanota/README.md
@@ -27,9 +27,7 @@
## 解法
-
-
-**方法一:递归**
+### 方法一:递归
我们设计一个函数 $dfs(n, a, b, c)$,表示将 $n$ 个盘子从 $a$ 移动到 $c$,其中 $b$ 为辅助柱子。
@@ -37,30 +35,8 @@
时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 是盘子的数目。
-**方法二:迭代(栈)**
-
-我们可以用栈来模拟递归的过程。
-
-我们定义一个结构体 $Task$,表示一个任务,其中 $n$ 表示盘子的数目,而 $a$, $b$, $c$ 表示三根柱子。
-
-我们将初始任务 $Task(len(A), A, B, C)$ 压入栈中,然后不断取出栈顶任务进行处理,直到栈为空。
-
-如果 $n = 1$,那么我们直接将盘子从 $a$ 移动到 $c$。
-
-否则,我们将三个子任务压入栈中,分别是:
-
-1. 将 $n - 1$ 个盘子从 $b$ 借助 $a$ 移动到 $c$;
-2. 将第 $n$ 个盘子从 $a$ 移动到 $c$;
-3. 将 $n - 1$ 个盘子从 $a$ 借助 $c$ 移动到 $b$。
-
-时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 是盘子的数目。
-
-### **Python3**
-
-
-
```python
class Solution:
def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
@@ -75,24 +51,6 @@ class Solution:
dfs(len(A), A, B, C)
```
-```python
-class Solution:
- def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
- stk = [(len(A), A, B, C)]
- while stk:
- n, a, b, c = stk.pop()
- if n == 1:
- c.append(a.pop())
- else:
- stk.append((n - 1, b, a, c))
- stk.append((1, a, b, c))
- stk.append((n - 1, a, c, b))
-```
-
-### **Java**
-
-
-
```java
class Solution {
public void hanota(List A, List B, List C) {
@@ -111,6 +69,99 @@ class Solution {
}
```
+```cpp
+class Solution {
+public:
+ void hanota(vector& A, vector& B, vector& C) {
+ function&, vector&, vector&)> dfs = [&](int n, vector& a, vector& b, vector& c) {
+ if (n == 1) {
+ c.push_back(a.back());
+ a.pop_back();
+ return;
+ }
+ dfs(n - 1, a, c, b);
+ c.push_back(a.back());
+ a.pop_back();
+ dfs(n - 1, b, a, c);
+ };
+ dfs(A.size(), A, B, C);
+ }
+};
+```
+
+```go
+func hanota(A []int, B []int, C []int) []int {
+ var dfs func(n int, a, b, c *[]int)
+ dfs = func(n int, a, b, c *[]int) {
+ if n == 1 {
+ *c = append(*c, (*a)[len(*a)-1])
+ *a = (*a)[:len(*a)-1]
+ return
+ }
+ dfs(n-1, a, c, b)
+ *c = append(*c, (*a)[len(*a)-1])
+ *a = (*a)[:len(*a)-1]
+ dfs(n-1, b, a, c)
+ }
+ dfs(len(A), &A, &B, &C)
+ return C
+}
+```
+
+```ts
+/**
+ Do not return anything, modify C in-place instead.
+ */
+function hanota(A: number[], B: number[], C: number[]): void {
+ const dfs = (n: number, a: number[], b: number[], c: number[]) => {
+ if (n === 1) {
+ c.push(a.pop()!);
+ return;
+ }
+ dfs(n - 1, a, c, b);
+ c.push(a.pop()!);
+ dfs(n - 1, b, a, c);
+ };
+ dfs(A.length, A, B, C);
+}
+```
+
+
+
+### 方法二:迭代(栈)
+
+我们可以用栈来模拟递归的过程。
+
+我们定义一个结构体 $Task$,表示一个任务,其中 $n$ 表示盘子的数目,而 $a$, $b$, $c$ 表示三根柱子。
+
+我们将初始任务 $Task(len(A), A, B, C)$ 压入栈中,然后不断取出栈顶任务进行处理,直到栈为空。
+
+如果 $n = 1$,那么我们直接将盘子从 $a$ 移动到 $c$。
+
+否则,我们将三个子任务压入栈中,分别是:
+
+1. 将 $n - 1$ 个盘子从 $b$ 借助 $a$ 移动到 $c$;
+2. 将第 $n$ 个盘子从 $a$ 移动到 $c$;
+3. 将 $n - 1$ 个盘子从 $a$ 借助 $c$ 移动到 $b$。
+
+时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 是盘子的数目。
+
+
+
+```python
+class Solution:
+ def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
+ stk = [(len(A), A, B, C)]
+ while stk:
+ n, a, b, c = stk.pop()
+ if n == 1:
+ c.append(a.pop())
+ else:
+ stk.append((n - 1, b, a, c))
+ stk.append((1, a, b, c))
+ stk.append((n - 1, a, c, b))
+```
+
```java
class Solution {
public void hanota(List A, List B, List C) {
@@ -148,28 +199,6 @@ class Task {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- void hanota(vector& A, vector& B, vector& C) {
- function&, vector&, vector&)> dfs = [&](int n, vector& a, vector& b, vector& c) {
- if (n == 1) {
- c.push_back(a.back());
- a.pop_back();
- return;
- }
- dfs(n - 1, a, c, b);
- c.push_back(a.back());
- a.pop_back();
- dfs(n - 1, b, a, c);
- };
- dfs(A.size(), A, B, C);
- }
-};
-```
-
```cpp
struct Task {
int n;
@@ -199,27 +228,6 @@ public:
};
```
-### **Go**
-
-```go
-func hanota(A []int, B []int, C []int) []int {
- var dfs func(n int, a, b, c *[]int)
- dfs = func(n int, a, b, c *[]int) {
- if n == 1 {
- *c = append(*c, (*a)[len(*a)-1])
- *a = (*a)[:len(*a)-1]
- return
- }
- dfs(n-1, a, c, b)
- *c = append(*c, (*a)[len(*a)-1])
- *a = (*a)[:len(*a)-1]
- dfs(n-1, b, a, c)
- }
- dfs(len(A), &A, &B, &C)
- return C
-}
-```
-
```go
func hanota(A []int, B []int, C []int) []int {
stk := []Task{{len(A), &A, &B, &C}}
@@ -244,26 +252,6 @@ type Task struct {
}
```
-### **TypeScript**
-
-```ts
-/**
- Do not return anything, modify C in-place instead.
- */
-function hanota(A: number[], B: number[], C: number[]): void {
- const dfs = (n: number, a: number[], b: number[], c: number[]) => {
- if (n === 1) {
- c.push(a.pop()!);
- return;
- }
- dfs(n - 1, a, c, b);
- c.push(a.pop()!);
- dfs(n - 1, b, a, c);
- };
- dfs(A.length, A, B, C);
-}
-```
-
```ts
/**
Do not return anything, modify C in-place instead.
@@ -283,10 +271,6 @@ function hanota(A: number[], B: number[], C: number[]): void {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.06.Hanota/README_EN.md b/lcci/08.06.Hanota/README_EN.md
index 68e2482b327db..e5a37b2b466a6 100644
--- a/lcci/08.06.Hanota/README_EN.md
+++ b/lcci/08.06.Hanota/README_EN.md
@@ -32,7 +32,7 @@
## Solutions
-**Solution 1: Recursion**
+### Solution 1: Recursion
We design a function $dfs(n, a, b, c)$, which represents moving $n$ disks from $a$ to $c$, with $b$ as the auxiliary rod.
@@ -40,28 +40,8 @@ First, we move $n - 1$ disks from $a$ to $b$, then move the $n$-th disk from $a$
The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Here, $n$ is the number of disks.
-**Solution 2: Iteration (Stack)**
-
-We can use a stack to simulate the recursive process.
-
-We define a struct $Task$, which represents a task, where $n$ represents the number of disks, and $a$, $b$, $c$ represent the three rods.
-
-We push the initial task $Task(len(A), A, B, C)$ into the stack, and then continuously process the task at the top of the stack until the stack is empty.
-
-If $n = 1$, then we directly move the disk from $a$ to $c$.
-
-Otherwise, we push three subtasks into the stack, which are:
-
-1. Move $n - 1$ disks from $b$ to $c$ with the help of $a$;
-2. Move the $n$-th disk from $a$ to $c$;
-3. Move $n - 1$ disks from $a$ to $b$ with the help of $c$.
-
-The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Here, $n$ is the number of disks.
-
-### **Python3**
-
```python
class Solution:
def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
@@ -76,22 +56,6 @@ class Solution:
dfs(len(A), A, B, C)
```
-```python
-class Solution:
- def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
- stk = [(len(A), A, B, C)]
- while stk:
- n, a, b, c = stk.pop()
- if n == 1:
- c.append(a.pop())
- else:
- stk.append((n - 1, b, a, c))
- stk.append((1, a, b, c))
- stk.append((n - 1, a, c, b))
-```
-
-### **Java**
-
```java
class Solution {
public void hanota(List A, List B, List C) {
@@ -110,6 +74,99 @@ class Solution {
}
```
+```cpp
+class Solution {
+public:
+ void hanota(vector& A, vector& B, vector& C) {
+ function&, vector&, vector&)> dfs = [&](int n, vector& a, vector& b, vector& c) {
+ if (n == 1) {
+ c.push_back(a.back());
+ a.pop_back();
+ return;
+ }
+ dfs(n - 1, a, c, b);
+ c.push_back(a.back());
+ a.pop_back();
+ dfs(n - 1, b, a, c);
+ };
+ dfs(A.size(), A, B, C);
+ }
+};
+```
+
+```go
+func hanota(A []int, B []int, C []int) []int {
+ var dfs func(n int, a, b, c *[]int)
+ dfs = func(n int, a, b, c *[]int) {
+ if n == 1 {
+ *c = append(*c, (*a)[len(*a)-1])
+ *a = (*a)[:len(*a)-1]
+ return
+ }
+ dfs(n-1, a, c, b)
+ *c = append(*c, (*a)[len(*a)-1])
+ *a = (*a)[:len(*a)-1]
+ dfs(n-1, b, a, c)
+ }
+ dfs(len(A), &A, &B, &C)
+ return C
+}
+```
+
+```ts
+/**
+ Do not return anything, modify C in-place instead.
+ */
+function hanota(A: number[], B: number[], C: number[]): void {
+ const dfs = (n: number, a: number[], b: number[], c: number[]) => {
+ if (n === 1) {
+ c.push(a.pop()!);
+ return;
+ }
+ dfs(n - 1, a, c, b);
+ c.push(a.pop()!);
+ dfs(n - 1, b, a, c);
+ };
+ dfs(A.length, A, B, C);
+}
+```
+
+
+
+### Solution 2: Iteration (Stack)
+
+We can use a stack to simulate the recursive process.
+
+We define a struct $Task$, which represents a task, where $n$ represents the number of disks, and $a$, $b$, $c$ represent the three rods.
+
+We push the initial task $Task(len(A), A, B, C)$ into the stack, and then continuously process the task at the top of the stack until the stack is empty.
+
+If $n = 1$, then we directly move the disk from $a$ to $c$.
+
+Otherwise, we push three subtasks into the stack, which are:
+
+1. Move $n - 1$ disks from $b$ to $c$ with the help of $a$;
+2. Move the $n$-th disk from $a$ to $c$;
+3. Move $n - 1$ disks from $a$ to $b$ with the help of $c$.
+
+The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Here, $n$ is the number of disks.
+
+
+
+```python
+class Solution:
+ def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
+ stk = [(len(A), A, B, C)]
+ while stk:
+ n, a, b, c = stk.pop()
+ if n == 1:
+ c.append(a.pop())
+ else:
+ stk.append((n - 1, b, a, c))
+ stk.append((1, a, b, c))
+ stk.append((n - 1, a, c, b))
+```
+
```java
class Solution {
public void hanota(List A, List B, List C) {
@@ -147,28 +204,6 @@ class Task {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- void hanota(vector& A, vector& B, vector& C) {
- function&, vector&, vector&)> dfs = [&](int n, vector& a, vector& b, vector& c) {
- if (n == 1) {
- c.push_back(a.back());
- a.pop_back();
- return;
- }
- dfs(n - 1, a, c, b);
- c.push_back(a.back());
- a.pop_back();
- dfs(n - 1, b, a, c);
- };
- dfs(A.size(), A, B, C);
- }
-};
-```
-
```cpp
struct Task {
int n;
@@ -198,27 +233,6 @@ public:
};
```
-### **Go**
-
-```go
-func hanota(A []int, B []int, C []int) []int {
- var dfs func(n int, a, b, c *[]int)
- dfs = func(n int, a, b, c *[]int) {
- if n == 1 {
- *c = append(*c, (*a)[len(*a)-1])
- *a = (*a)[:len(*a)-1]
- return
- }
- dfs(n-1, a, c, b)
- *c = append(*c, (*a)[len(*a)-1])
- *a = (*a)[:len(*a)-1]
- dfs(n-1, b, a, c)
- }
- dfs(len(A), &A, &B, &C)
- return C
-}
-```
-
```go
func hanota(A []int, B []int, C []int) []int {
stk := []Task{{len(A), &A, &B, &C}}
@@ -243,26 +257,6 @@ type Task struct {
}
```
-### **TypeScript**
-
-```ts
-/**
- Do not return anything, modify C in-place instead.
- */
-function hanota(A: number[], B: number[], C: number[]): void {
- const dfs = (n: number, a: number[], b: number[], c: number[]) => {
- if (n === 1) {
- c.push(a.pop()!);
- return;
- }
- dfs(n - 1, a, c, b);
- c.push(a.pop()!);
- dfs(n - 1, b, a, c);
- };
- dfs(A.length, A, B, C);
-}
-```
-
```ts
/**
Do not return anything, modify C in-place instead.
@@ -282,10 +276,6 @@ function hanota(A: number[], B: number[], C: number[]): void {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.07.Permutation I/README.md b/lcci/08.07.Permutation I/README.md
index 90443c5f7c55d..803eefe364579 100644
--- a/lcci/08.07.Permutation I/README.md
+++ b/lcci/08.07.Permutation I/README.md
@@ -30,16 +30,10 @@
## 解法
-
-
-**方法一:回溯**
+### 方法一:回溯
-### **Python3**
-
-
-
```python
class Solution:
def permutation(self, S: str) -> List[str]:
@@ -63,10 +57,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
public String[] permutation(String S) {
@@ -96,42 +86,6 @@ class Solution {
}
```
-### **JavaSript**
-
-```js
-/**
- * @param {string} S
- * @return {string[]}
- */
-var permutation = function (S) {
- let res = [];
- let arr = [...S];
- let prev = [];
- let record = new Array(S.length).fill(false);
- dfs(arr, 0, prev, record, res);
- return res;
-};
-
-function dfs(arr, depth, prev, record, res) {
- if (depth == arr.length) {
- res.push(prev.join(''));
- return;
- }
- for (let i = 0; i < arr.length; i++) {
- if (record[i]) {
- continue;
- }
- prev.push(arr[i]);
- record[i] = true;
- dfs(arr, depth + 1, prev, record, res);
- prev.pop();
- record[i] = false;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -160,8 +114,6 @@ public:
};
```
-### **Go**
-
```go
func permutation(S string) []string {
vis := make(map[byte]bool)
@@ -189,10 +141,38 @@ func permutation(S string) []string {
}
```
-### **...**
-
-```
+```js
+/**
+ * @param {string} S
+ * @return {string[]}
+ */
+var permutation = function (S) {
+ let res = [];
+ let arr = [...S];
+ let prev = [];
+ let record = new Array(S.length).fill(false);
+ dfs(arr, 0, prev, record, res);
+ return res;
+};
+function dfs(arr, depth, prev, record, res) {
+ if (depth == arr.length) {
+ res.push(prev.join(''));
+ return;
+ }
+ for (let i = 0; i < arr.length; i++) {
+ if (record[i]) {
+ continue;
+ }
+ prev.push(arr[i]);
+ record[i] = true;
+ dfs(arr, depth + 1, prev, record, res);
+ prev.pop();
+ record[i] = false;
+ }
+}
```
+
+
diff --git a/lcci/08.07.Permutation I/README_EN.md b/lcci/08.07.Permutation I/README_EN.md
index 24cd06be08222..ac04b96e870c3 100644
--- a/lcci/08.07.Permutation I/README_EN.md
+++ b/lcci/08.07.Permutation I/README_EN.md
@@ -35,12 +35,10 @@
## Solutions
-Backtracking
+### Solution 1
-### **Python3**
-
```python
class Solution:
def permutation(self, S: str) -> List[str]:
@@ -64,8 +62,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
public String[] permutation(String S) {
@@ -95,42 +91,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {string} S
- * @return {string[]}
- */
-var permutation = function (S) {
- let res = [];
- let arr = [...S];
- let prev = [];
- let record = new Array(S.length).fill(false);
- dfs(arr, 0, prev, record, res);
- return res;
-};
-
-function dfs(arr, depth, prev, record, res) {
- if (depth == arr.length) {
- res.push(prev.join(''));
- return;
- }
- for (let i = 0; i < arr.length; i++) {
- if (record[i]) {
- continue;
- }
- prev.push(arr[i]);
- record[i] = true;
- dfs(arr, depth + 1, prev, record, res);
- prev.pop();
- record[i] = false;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -159,8 +119,6 @@ public:
};
```
-### **Go**
-
```go
func permutation(S string) []string {
vis := make(map[byte]bool)
@@ -188,10 +146,38 @@ func permutation(S string) []string {
}
```
-### **...**
-
-```
+```js
+/**
+ * @param {string} S
+ * @return {string[]}
+ */
+var permutation = function (S) {
+ let res = [];
+ let arr = [...S];
+ let prev = [];
+ let record = new Array(S.length).fill(false);
+ dfs(arr, 0, prev, record, res);
+ return res;
+};
+function dfs(arr, depth, prev, record, res) {
+ if (depth == arr.length) {
+ res.push(prev.join(''));
+ return;
+ }
+ for (let i = 0; i < arr.length; i++) {
+ if (record[i]) {
+ continue;
+ }
+ prev.push(arr[i]);
+ record[i] = true;
+ dfs(arr, depth + 1, prev, record, res);
+ prev.pop();
+ record[i] = false;
+ }
+}
```
+
+
diff --git a/lcci/08.08.Permutation II/README.md b/lcci/08.08.Permutation II/README.md
index 976fee76c19f6..98fdc519f076a 100644
--- a/lcci/08.08.Permutation II/README.md
+++ b/lcci/08.08.Permutation II/README.md
@@ -23,9 +23,7 @@
## 解法
-
-
-**方法一:排序 + 回溯**
+### 方法一:排序 + 回溯
我们可以先对字符串按照字符进行排序,这样就可以将重复的字符放在一起,方便我们进行去重。
@@ -40,10 +38,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def permutation(self, S: str) -> List[str]:
@@ -68,10 +62,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
private int n;
@@ -108,8 +98,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -142,8 +130,6 @@ public:
};
```
-### **Go**
-
```go
func permutation(S string) (ans []string) {
cs := []byte(S)
@@ -173,8 +159,6 @@ func permutation(S string) (ans []string) {
}
```
-### **TypeScript**
-
```ts
function permutation(S: string): string[] {
const cs: string[] = S.split('').sort();
@@ -203,8 +187,6 @@ function permutation(S: string): string[] {
}
```
-### **JavaScript**
-
```js
/**
* @param {string} S
@@ -237,10 +219,6 @@ var permutation = function (S) {
};
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.08.Permutation II/README_EN.md b/lcci/08.08.Permutation II/README_EN.md
index 1c32e194558ce..3ad9deed64ae1 100644
--- a/lcci/08.08.Permutation II/README_EN.md
+++ b/lcci/08.08.Permutation II/README_EN.md
@@ -29,7 +29,7 @@
## Solutions
-**Solution 1: Sorting + Backtracking**
+### Solution 1: Sorting + Backtracking
We can first sort the string by characters, which allows us to put duplicate characters together and makes it easier for us to remove duplicates.
@@ -44,8 +44,6 @@ The time complexity is $O(n \times n!)$, and the space complexity is $O(n)$. Her
-### **Python3**
-
```python
class Solution:
def permutation(self, S: str) -> List[str]:
@@ -70,8 +68,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
private int n;
@@ -108,8 +104,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -142,8 +136,6 @@ public:
};
```
-### **Go**
-
```go
func permutation(S string) (ans []string) {
cs := []byte(S)
@@ -173,8 +165,6 @@ func permutation(S string) (ans []string) {
}
```
-### **TypeScript**
-
```ts
function permutation(S: string): string[] {
const cs: string[] = S.split('').sort();
@@ -203,8 +193,6 @@ function permutation(S: string): string[] {
}
```
-### **JavaScript**
-
```js
/**
* @param {string} S
@@ -237,10 +225,6 @@ var permutation = function (S) {
};
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.09.Bracket/README.md b/lcci/08.09.Bracket/README.md
index 5bcf4043d6206..13d5c5286127c 100644
--- a/lcci/08.09.Bracket/README.md
+++ b/lcci/08.09.Bracket/README.md
@@ -23,9 +23,7 @@
## 解法
-
-
-**方法一:DFS + 剪枝**
+### 方法一:DFS + 剪枝
题目中 $n$ 的范围为 $[1, 8]$,因此我们直接通过“暴力搜索 + 剪枝”的方式快速解决本题。
@@ -40,10 +38,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
@@ -61,10 +55,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
private List ans = new ArrayList<>();
@@ -90,8 +80,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -113,8 +101,6 @@ public:
};
```
-### **Go**
-
```go
func generateParenthesis(n int) []string {
ans := []string{}
@@ -135,33 +121,6 @@ func generateParenthesis(n int) []string {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number} n
- * @return {string[]}
- */
-var generateParenthesis = function (n) {
- function dfs(l, r, t) {
- if (l > n || r > n || l < r) {
- return;
- }
- if (l == n && r == n) {
- ans.push(t);
- return;
- }
- dfs(l + 1, r, t + '(');
- dfs(l, r + 1, t + ')');
- }
- let ans = [];
- dfs(0, 0, '');
- return ans;
-};
-```
-
-### **TypeScript**
-
```ts
function generateParenthesis(n: number): string[] {
function dfs(l, r, t) {
@@ -181,8 +140,6 @@ function generateParenthesis(n: number): string[] {
}
```
-### **Rust**
-
```rust
impl Solution {
fn dfs(left: i32, right: i32, s: &mut String, res: &mut Vec) {
@@ -210,10 +167,29 @@ impl Solution {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * @param {number} n
+ * @return {string[]}
+ */
+var generateParenthesis = function (n) {
+ function dfs(l, r, t) {
+ if (l > n || r > n || l < r) {
+ return;
+ }
+ if (l == n && r == n) {
+ ans.push(t);
+ return;
+ }
+ dfs(l + 1, r, t + '(');
+ dfs(l, r + 1, t + ')');
+ }
+ let ans = [];
+ dfs(0, 0, '');
+ return ans;
+};
```
+
+
diff --git a/lcci/08.09.Bracket/README_EN.md b/lcci/08.09.Bracket/README_EN.md
index cc2b905c877e9..034e23dfc789c 100644
--- a/lcci/08.09.Bracket/README_EN.md
+++ b/lcci/08.09.Bracket/README_EN.md
@@ -30,7 +30,7 @@
## Solutions
-**Solution 1: DFS + Pruning**
+### Solution 1: DFS + Pruning
The range of $n$ in the problem is $[1, 8]$, so we can directly solve this problem quickly through "brute force search + pruning".
@@ -45,8 +45,6 @@ The time complexity is $O(2^{n\times 2} \times n)$, and the space complexity is
-### **Python3**
-
```python
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
@@ -64,8 +62,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
private List ans = new ArrayList<>();
@@ -91,8 +87,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -114,8 +108,6 @@ public:
};
```
-### **Go**
-
```go
func generateParenthesis(n int) []string {
ans := []string{}
@@ -136,33 +128,6 @@ func generateParenthesis(n int) []string {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number} n
- * @return {string[]}
- */
-var generateParenthesis = function (n) {
- function dfs(l, r, t) {
- if (l > n || r > n || l < r) {
- return;
- }
- if (l == n && r == n) {
- ans.push(t);
- return;
- }
- dfs(l + 1, r, t + '(');
- dfs(l, r + 1, t + ')');
- }
- let ans = [];
- dfs(0, 0, '');
- return ans;
-};
-```
-
-### **TypeScript**
-
```ts
function generateParenthesis(n: number): string[] {
function dfs(l, r, t) {
@@ -182,8 +147,6 @@ function generateParenthesis(n: number): string[] {
}
```
-### **Rust**
-
```rust
impl Solution {
fn dfs(left: i32, right: i32, s: &mut String, res: &mut Vec) {
@@ -211,10 +174,29 @@ impl Solution {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * @param {number} n
+ * @return {string[]}
+ */
+var generateParenthesis = function (n) {
+ function dfs(l, r, t) {
+ if (l > n || r > n || l < r) {
+ return;
+ }
+ if (l == n && r == n) {
+ ans.push(t);
+ return;
+ }
+ dfs(l + 1, r, t + '(');
+ dfs(l, r + 1, t + ')');
+ }
+ let ans = [];
+ dfs(0, 0, '');
+ return ans;
+};
```
+
+
diff --git a/lcci/08.10.Color Fill/README.md b/lcci/08.10.Color Fill/README.md
index 6b5764de99983..5d0f7a5fd7182 100644
--- a/lcci/08.10.Color Fill/README.md
+++ b/lcci/08.10.Color Fill/README.md
@@ -31,9 +31,7 @@ sr = 1, sc = 1, newColor = 2
## 解法
-
-
-**方法一:Flood fill 算法**
+### 方法一:Flood fill 算法
Flood fill 算法是从一个区域中提取若干个连通的点与其他相邻区域区分开(或分别染成不同颜色)的经典算法。因为其思路类似洪水从一个区域扩散到所有能到达的区域而得名。
@@ -43,10 +41,6 @@ Flood fill 算法是从一个区域中提取若干个连通的点与其他相邻
-### **Python3**
-
-
-
```python
class Solution:
def floodFill(
@@ -71,31 +65,6 @@ class Solution:
return image
```
-```python
-class Solution:
- def floodFill(
- self, image: List[List[int]], sr: int, sc: int, newColor: int
- ) -> List[List[int]]:
- if image[sr][sc] == newColor:
- return image
- q = deque([(sr, sc)])
- oc = image[sr][sc]
- image[sr][sc] = newColor
- dirs = (-1, 0, 1, 0, -1)
- while q:
- i, j = q.popleft()
- for a, b in pairwise(dirs):
- x, y = i + a, j + b
- if 0 <= x < len(image) and 0 <= y < len(image[0]) and image[x][y] == oc:
- q.append((x, y))
- image[x][y] = newColor
- return image
-```
-
-### **Java**
-
-
-
```java
class Solution {
private int[] dirs = {-1, 0, 1, 0, -1};
@@ -124,36 +93,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
- if (image[sr][sc] == newColor) {
- return image;
- }
- Deque q = new ArrayDeque<>();
- q.offer(new int[] {sr, sc});
- int oc = image[sr][sc];
- image[sr][sc] = newColor;
- int[] dirs = {-1, 0, 1, 0, -1};
- while (!q.isEmpty()) {
- int[] p = q.poll();
- int i = p[0], j = p[1];
- for (int k = 0; k < 4; ++k) {
- int x = i + dirs[k], y = j + dirs[k + 1];
- if (x >= 0 && x < image.length && y >= 0 && y < image[0].length
- && image[x][y] == oc) {
- q.offer(new int[] {x, y});
- image[x][y] = newColor;
- }
- }
- }
- return image;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -176,35 +115,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- vector> floodFill(vector>& image, int sr, int sc, int newColor) {
- if (image[sr][sc] == newColor) return image;
- int oc = image[sr][sc];
- image[sr][sc] = newColor;
- queue> q;
- q.push({sr, sc});
- int dirs[5] = {-1, 0, 1, 0, -1};
- while (!q.empty()) {
- auto [a, b] = q.front();
- q.pop();
- for (int k = 0; k < 4; ++k) {
- int x = a + dirs[k];
- int y = b + dirs[k + 1];
- if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oc) {
- q.push({x, y});
- image[x][y] = newColor;
- }
- }
- }
- return image;
- }
-};
-```
-
-### **Go**
-
```go
func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
oc := image[sr][sc]
@@ -225,32 +135,6 @@ func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
}
```
-```go
-func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
- if image[sr][sc] == newColor {
- return image
- }
- oc := image[sr][sc]
- q := [][]int{[]int{sr, sc}}
- image[sr][sc] = newColor
- dirs := []int{-1, 0, 1, 0, -1}
- for len(q) > 0 {
- p := q[0]
- q = q[1:]
- for k := 0; k < 4; k++ {
- x, y := p[0]+dirs[k], p[1]+dirs[k+1]
- if x >= 0 && x < len(image) && y >= 0 && y < len(image[0]) && image[x][y] == oc {
- q = append(q, []int{x, y})
- image[x][y] = newColor
- }
- }
- }
- return image
-}
-```
-
-### **Rust**
-
```rust
impl Solution {
fn dfs(i: usize, j: usize, target: i32, new_color: i32, image: &mut Vec>) {
@@ -284,10 +168,112 @@ impl Solution {
}
```
-### **...**
+
+
+### 方法二
+
+
+
+```python
+class Solution:
+ def floodFill(
+ self, image: List[List[int]], sr: int, sc: int, newColor: int
+ ) -> List[List[int]]:
+ if image[sr][sc] == newColor:
+ return image
+ q = deque([(sr, sc)])
+ oc = image[sr][sc]
+ image[sr][sc] = newColor
+ dirs = (-1, 0, 1, 0, -1)
+ while q:
+ i, j = q.popleft()
+ for a, b in pairwise(dirs):
+ x, y = i + a, j + b
+ if 0 <= x < len(image) and 0 <= y < len(image[0]) and image[x][y] == oc:
+ q.append((x, y))
+ image[x][y] = newColor
+ return image
+```
+
+```java
+class Solution {
+ public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
+ if (image[sr][sc] == newColor) {
+ return image;
+ }
+ Deque q = new ArrayDeque<>();
+ q.offer(new int[] {sr, sc});
+ int oc = image[sr][sc];
+ image[sr][sc] = newColor;
+ int[] dirs = {-1, 0, 1, 0, -1};
+ while (!q.isEmpty()) {
+ int[] p = q.poll();
+ int i = p[0], j = p[1];
+ for (int k = 0; k < 4; ++k) {
+ int x = i + dirs[k], y = j + dirs[k + 1];
+ if (x >= 0 && x < image.length && y >= 0 && y < image[0].length
+ && image[x][y] == oc) {
+ q.offer(new int[] {x, y});
+ image[x][y] = newColor;
+ }
+ }
+ }
+ return image;
+ }
+}
+```
+```cpp
+class Solution {
+public:
+ vector> floodFill(vector>& image, int sr, int sc, int newColor) {
+ if (image[sr][sc] == newColor) return image;
+ int oc = image[sr][sc];
+ image[sr][sc] = newColor;
+ queue> q;
+ q.push({sr, sc});
+ int dirs[5] = {-1, 0, 1, 0, -1};
+ while (!q.empty()) {
+ auto [a, b] = q.front();
+ q.pop();
+ for (int k = 0; k < 4; ++k) {
+ int x = a + dirs[k];
+ int y = b + dirs[k + 1];
+ if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oc) {
+ q.push({x, y});
+ image[x][y] = newColor;
+ }
+ }
+ }
+ return image;
+ }
+};
```
+```go
+func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
+ if image[sr][sc] == newColor {
+ return image
+ }
+ oc := image[sr][sc]
+ q := [][]int{[]int{sr, sc}}
+ image[sr][sc] = newColor
+ dirs := []int{-1, 0, 1, 0, -1}
+ for len(q) > 0 {
+ p := q[0]
+ q = q[1:]
+ for k := 0; k < 4; k++ {
+ x, y := p[0]+dirs[k], p[1]+dirs[k+1]
+ if x >= 0 && x < len(image) && y >= 0 && y < len(image[0]) && image[x][y] == oc {
+ q = append(q, []int{x, y})
+ image[x][y] = newColor
+ }
+ }
+ }
+ return image
+}
```
+
+
diff --git a/lcci/08.10.Color Fill/README_EN.md b/lcci/08.10.Color Fill/README_EN.md
index 2b764190e6c0a..fdf2abebfbf34 100644
--- a/lcci/08.10.Color Fill/README_EN.md
+++ b/lcci/08.10.Color Fill/README_EN.md
@@ -38,7 +38,7 @@ to the starting pixel.
## Solutions
-**Solution 1: Flood Fill Algorithm**
+### Solution 1: Flood Fill Algorithm
The Flood Fill algorithm is a classic algorithm used to extract several connected points from a region and distinguish them from other adjacent regions (or color them differently). It is named for its strategy, which is similar to a flood spreading from one area to all reachable areas.
@@ -48,8 +48,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times
-### **Python3**
-
```python
class Solution:
def floodFill(
@@ -74,29 +72,6 @@ class Solution:
return image
```
-```python
-class Solution:
- def floodFill(
- self, image: List[List[int]], sr: int, sc: int, newColor: int
- ) -> List[List[int]]:
- if image[sr][sc] == newColor:
- return image
- q = deque([(sr, sc)])
- oc = image[sr][sc]
- image[sr][sc] = newColor
- dirs = (-1, 0, 1, 0, -1)
- while q:
- i, j = q.popleft()
- for a, b in pairwise(dirs):
- x, y = i + a, j + b
- if 0 <= x < len(image) and 0 <= y < len(image[0]) and image[x][y] == oc:
- q.append((x, y))
- image[x][y] = newColor
- return image
-```
-
-### **Java**
-
```java
class Solution {
private int[] dirs = {-1, 0, 1, 0, -1};
@@ -125,36 +100,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
- if (image[sr][sc] == newColor) {
- return image;
- }
- Deque q = new ArrayDeque<>();
- q.offer(new int[] {sr, sc});
- int oc = image[sr][sc];
- image[sr][sc] = newColor;
- int[] dirs = {-1, 0, 1, 0, -1};
- while (!q.isEmpty()) {
- int[] p = q.poll();
- int i = p[0], j = p[1];
- for (int k = 0; k < 4; ++k) {
- int x = i + dirs[k], y = j + dirs[k + 1];
- if (x >= 0 && x < image.length && y >= 0 && y < image[0].length
- && image[x][y] == oc) {
- q.offer(new int[] {x, y});
- image[x][y] = newColor;
- }
- }
- }
- return image;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -177,35 +122,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- vector> floodFill(vector>& image, int sr, int sc, int newColor) {
- if (image[sr][sc] == newColor) return image;
- int oc = image[sr][sc];
- image[sr][sc] = newColor;
- queue> q;
- q.push({sr, sc});
- int dirs[5] = {-1, 0, 1, 0, -1};
- while (!q.empty()) {
- auto [a, b] = q.front();
- q.pop();
- for (int k = 0; k < 4; ++k) {
- int x = a + dirs[k];
- int y = b + dirs[k + 1];
- if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oc) {
- q.push({x, y});
- image[x][y] = newColor;
- }
- }
- }
- return image;
- }
-};
-```
-
-### **Go**
-
```go
func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
oc := image[sr][sc]
@@ -226,32 +142,6 @@ func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
}
```
-```go
-func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
- if image[sr][sc] == newColor {
- return image
- }
- oc := image[sr][sc]
- q := [][]int{[]int{sr, sc}}
- image[sr][sc] = newColor
- dirs := []int{-1, 0, 1, 0, -1}
- for len(q) > 0 {
- p := q[0]
- q = q[1:]
- for k := 0; k < 4; k++ {
- x, y := p[0]+dirs[k], p[1]+dirs[k+1]
- if x >= 0 && x < len(image) && y >= 0 && y < len(image[0]) && image[x][y] == oc {
- q = append(q, []int{x, y})
- image[x][y] = newColor
- }
- }
- }
- return image
-}
-```
-
-### **Rust**
-
```rust
impl Solution {
fn dfs(i: usize, j: usize, target: i32, new_color: i32, image: &mut Vec>) {
@@ -285,10 +175,112 @@ impl Solution {
}
```
-### **...**
+
+
+### Solution 2
+
+
+```python
+class Solution:
+ def floodFill(
+ self, image: List[List[int]], sr: int, sc: int, newColor: int
+ ) -> List[List[int]]:
+ if image[sr][sc] == newColor:
+ return image
+ q = deque([(sr, sc)])
+ oc = image[sr][sc]
+ image[sr][sc] = newColor
+ dirs = (-1, 0, 1, 0, -1)
+ while q:
+ i, j = q.popleft()
+ for a, b in pairwise(dirs):
+ x, y = i + a, j + b
+ if 0 <= x < len(image) and 0 <= y < len(image[0]) and image[x][y] == oc:
+ q.append((x, y))
+ image[x][y] = newColor
+ return image
```
+```java
+class Solution {
+ public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
+ if (image[sr][sc] == newColor) {
+ return image;
+ }
+ Deque q = new ArrayDeque<>();
+ q.offer(new int[] {sr, sc});
+ int oc = image[sr][sc];
+ image[sr][sc] = newColor;
+ int[] dirs = {-1, 0, 1, 0, -1};
+ while (!q.isEmpty()) {
+ int[] p = q.poll();
+ int i = p[0], j = p[1];
+ for (int k = 0; k < 4; ++k) {
+ int x = i + dirs[k], y = j + dirs[k + 1];
+ if (x >= 0 && x < image.length && y >= 0 && y < image[0].length
+ && image[x][y] == oc) {
+ q.offer(new int[] {x, y});
+ image[x][y] = newColor;
+ }
+ }
+ }
+ return image;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ vector> floodFill(vector>& image, int sr, int sc, int newColor) {
+ if (image[sr][sc] == newColor) return image;
+ int oc = image[sr][sc];
+ image[sr][sc] = newColor;
+ queue> q;
+ q.push({sr, sc});
+ int dirs[5] = {-1, 0, 1, 0, -1};
+ while (!q.empty()) {
+ auto [a, b] = q.front();
+ q.pop();
+ for (int k = 0; k < 4; ++k) {
+ int x = a + dirs[k];
+ int y = b + dirs[k + 1];
+ if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oc) {
+ q.push({x, y});
+ image[x][y] = newColor;
+ }
+ }
+ }
+ return image;
+ }
+};
+```
+
+```go
+func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
+ if image[sr][sc] == newColor {
+ return image
+ }
+ oc := image[sr][sc]
+ q := [][]int{[]int{sr, sc}}
+ image[sr][sc] = newColor
+ dirs := []int{-1, 0, 1, 0, -1}
+ for len(q) > 0 {
+ p := q[0]
+ q = q[1:]
+ for k := 0; k < 4; k++ {
+ x, y := p[0]+dirs[k], p[1]+dirs[k+1]
+ if x >= 0 && x < len(image) && y >= 0 && y < len(image[0]) && image[x][y] == oc {
+ q = append(q, []int{x, y})
+ image[x][y] = newColor
+ }
+ }
+ }
+ return image
+}
```
+
+
diff --git a/lcci/08.11.Coin/README.md b/lcci/08.11.Coin/README.md
index e976726398bdd..054fd16eb4902 100644
--- a/lcci/08.11.Coin/README.md
+++ b/lcci/08.11.Coin/README.md
@@ -33,9 +33,7 @@
## 解法
-
-
-**方法一:动态规划**
+### 方法一:动态规划
我们定义 $f[i][j]$ 表示只使用前 $i$ 种硬币的情况下,凑成总金额为 $j$ 的方案数。初始时 $f[0][0]=1$,其余元素都为 $0$。答案为 $f[4][n]$。
@@ -69,10 +67,6 @@ $$
-### **Python3**
-
-
-
```python
class Solution:
def waysToChange(self, n: int) -> int:
@@ -88,22 +82,6 @@ class Solution:
return f[-1][n]
```
-```python
-class Solution:
- def waysToChange(self, n: int) -> int:
- mod = 10**9 + 7
- coins = [25, 10, 5, 1]
- f = [1] + [0] * n
- for c in coins:
- for j in range(c, n + 1):
- f[j] = (f[j] + f[j - c]) % mod
- return f[n]
-```
-
-### **Java**
-
-
-
```java
class Solution {
public int waysToChange(int n) {
@@ -124,25 +102,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int waysToChange(int n) {
- final int mod = (int) 1e9 + 7;
- int[] coins = {25, 10, 5, 1};
- int[] f = new int[n + 1];
- f[0] = 1;
- for (int c : coins) {
- for (int j = c; j <= n; ++j) {
- f[j] = (f[j] + f[j - c]) % mod;
- }
- }
- return f[n];
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -165,27 +124,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- int waysToChange(int n) {
- const int mod = 1e9 + 7;
- vector coins = {25, 10, 5, 1};
- int f[n + 1];
- memset(f, 0, sizeof(f));
- f[0] = 1;
- for (int c : coins) {
- for (int j = c; j <= n; ++j) {
- f[j] = (f[j] + f[j - c]) % mod;
- }
- }
- return f[n];
- }
-};
-```
-
-### **Go**
-
```go
func waysToChange(n int) int {
const mod int = 1e9 + 7
@@ -207,23 +145,6 @@ func waysToChange(n int) int {
}
```
-```go
-func waysToChange(n int) int {
- const mod int = 1e9 + 7
- coins := []int{25, 10, 5, 1}
- f := make([]int, n+1)
- f[0] = 1
- for _, c := range coins {
- for j := c; j <= n; j++ {
- f[j] = (f[j] + f[j-c]) % mod
- }
- }
- return f[n]
-}
-```
-
-### **TypeScript**
-
```ts
function waysToChange(n: number): number {
const mod = 10 ** 9 + 7;
@@ -244,6 +165,75 @@ function waysToChange(n: number): number {
}
```
+
+
+### 方法二
+
+
+
+```python
+class Solution:
+ def waysToChange(self, n: int) -> int:
+ mod = 10**9 + 7
+ coins = [25, 10, 5, 1]
+ f = [1] + [0] * n
+ for c in coins:
+ for j in range(c, n + 1):
+ f[j] = (f[j] + f[j - c]) % mod
+ return f[n]
+```
+
+```java
+class Solution {
+ public int waysToChange(int n) {
+ final int mod = (int) 1e9 + 7;
+ int[] coins = {25, 10, 5, 1};
+ int[] f = new int[n + 1];
+ f[0] = 1;
+ for (int c : coins) {
+ for (int j = c; j <= n; ++j) {
+ f[j] = (f[j] + f[j - c]) % mod;
+ }
+ }
+ return f[n];
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ int waysToChange(int n) {
+ const int mod = 1e9 + 7;
+ vector coins = {25, 10, 5, 1};
+ int f[n + 1];
+ memset(f, 0, sizeof(f));
+ f[0] = 1;
+ for (int c : coins) {
+ for (int j = c; j <= n; ++j) {
+ f[j] = (f[j] + f[j - c]) % mod;
+ }
+ }
+ return f[n];
+ }
+};
+```
+
+```go
+func waysToChange(n int) int {
+ const mod int = 1e9 + 7
+ coins := []int{25, 10, 5, 1}
+ f := make([]int, n+1)
+ f[0] = 1
+ for _, c := range coins {
+ for j := c; j <= n; j++ {
+ f[j] = (f[j] + f[j-c]) % mod
+ }
+ }
+ return f[n]
+}
+```
+
```ts
function waysToChange(n: number): number {
const mod = 10 ** 9 + 7;
@@ -259,10 +249,6 @@ function waysToChange(n: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.11.Coin/README_EN.md b/lcci/08.11.Coin/README_EN.md
index a6e5e9f4482c0..ba0955422b698 100644
--- a/lcci/08.11.Coin/README_EN.md
+++ b/lcci/08.11.Coin/README_EN.md
@@ -45,7 +45,7 @@
## Solutions
-**Solution 1: Dynamic Programming**
+### Solution 1: Dynamic Programming
We define $f[i][j]$ as the number of ways to make up the total amount $j$ using only the first $i$ types of coins. Initially, $f[0][0]=1$, and the rest of the elements are $0$. The answer is $f[4][n]$.
@@ -79,8 +79,6 @@ We notice that the calculation of $f[i][j]$ is only related to $f[i−1][..]$, s
-### **Python3**
-
```python
class Solution:
def waysToChange(self, n: int) -> int:
@@ -96,20 +94,6 @@ class Solution:
return f[-1][n]
```
-```python
-class Solution:
- def waysToChange(self, n: int) -> int:
- mod = 10**9 + 7
- coins = [25, 10, 5, 1]
- f = [1] + [0] * n
- for c in coins:
- for j in range(c, n + 1):
- f[j] = (f[j] + f[j - c]) % mod
- return f[n]
-```
-
-### **Java**
-
```java
class Solution {
public int waysToChange(int n) {
@@ -130,25 +114,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int waysToChange(int n) {
- final int mod = (int) 1e9 + 7;
- int[] coins = {25, 10, 5, 1};
- int[] f = new int[n + 1];
- f[0] = 1;
- for (int c : coins) {
- for (int j = c; j <= n; ++j) {
- f[j] = (f[j] + f[j - c]) % mod;
- }
- }
- return f[n];
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -171,27 +136,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- int waysToChange(int n) {
- const int mod = 1e9 + 7;
- vector coins = {25, 10, 5, 1};
- int f[n + 1];
- memset(f, 0, sizeof(f));
- f[0] = 1;
- for (int c : coins) {
- for (int j = c; j <= n; ++j) {
- f[j] = (f[j] + f[j - c]) % mod;
- }
- }
- return f[n];
- }
-};
-```
-
-### **Go**
-
```go
func waysToChange(n int) int {
const mod int = 1e9 + 7
@@ -213,23 +157,6 @@ func waysToChange(n int) int {
}
```
-```go
-func waysToChange(n int) int {
- const mod int = 1e9 + 7
- coins := []int{25, 10, 5, 1}
- f := make([]int, n+1)
- f[0] = 1
- for _, c := range coins {
- for j := c; j <= n; j++ {
- f[j] = (f[j] + f[j-c]) % mod
- }
- }
- return f[n]
-}
-```
-
-### **TypeScript**
-
```ts
function waysToChange(n: number): number {
const mod = 10 ** 9 + 7;
@@ -250,6 +177,75 @@ function waysToChange(n: number): number {
}
```
+
+
+### Solution 2
+
+
+
+```python
+class Solution:
+ def waysToChange(self, n: int) -> int:
+ mod = 10**9 + 7
+ coins = [25, 10, 5, 1]
+ f = [1] + [0] * n
+ for c in coins:
+ for j in range(c, n + 1):
+ f[j] = (f[j] + f[j - c]) % mod
+ return f[n]
+```
+
+```java
+class Solution {
+ public int waysToChange(int n) {
+ final int mod = (int) 1e9 + 7;
+ int[] coins = {25, 10, 5, 1};
+ int[] f = new int[n + 1];
+ f[0] = 1;
+ for (int c : coins) {
+ for (int j = c; j <= n; ++j) {
+ f[j] = (f[j] + f[j - c]) % mod;
+ }
+ }
+ return f[n];
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ int waysToChange(int n) {
+ const int mod = 1e9 + 7;
+ vector coins = {25, 10, 5, 1};
+ int f[n + 1];
+ memset(f, 0, sizeof(f));
+ f[0] = 1;
+ for (int c : coins) {
+ for (int j = c; j <= n; ++j) {
+ f[j] = (f[j] + f[j - c]) % mod;
+ }
+ }
+ return f[n];
+ }
+};
+```
+
+```go
+func waysToChange(n int) int {
+ const mod int = 1e9 + 7
+ coins := []int{25, 10, 5, 1}
+ f := make([]int, n+1)
+ f[0] = 1
+ for _, c := range coins {
+ for j := c; j <= n; j++ {
+ f[j] = (f[j] + f[j-c]) % mod
+ }
+ }
+ return f[n]
+}
+```
+
```ts
function waysToChange(n: number): number {
const mod = 10 ** 9 + 7;
@@ -265,10 +261,6 @@ function waysToChange(n: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.12.Eight Queens/README.md b/lcci/08.12.Eight Queens/README.md
index 4209a9185358f..2f0a2c8da482d 100644
--- a/lcci/08.12.Eight Queens/README.md
+++ b/lcci/08.12.Eight Queens/README.md
@@ -29,16 +29,10 @@
## 解法
-
-
-深度优先搜索 + 剪枝。
+### 方法一
-### **Python3**
-
-
-
```python
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
@@ -64,10 +58,6 @@ class Solution:
return res
```
-### **Java**
-
-
-
```java
class Solution {
public List> solveNQueens(int n) {
@@ -112,8 +102,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -145,8 +133,6 @@ public:
};
```
-### **Go**
-
```go
func solveNQueens(n int) [][]string {
res := [][]string{}
@@ -185,10 +171,58 @@ func dfs(u, n int, col, dg, udg []bool, g [][]string, res *[][]string) {
}
```
-### **...**
+```cs
+using System.Collections.Generic;
+using System.Text;
-```
+public class Solution {
+ private IList> results = new List>();
+ private int n;
+
+ public IList> SolveNQueens(int n) {
+ this.n = n;
+ Search(new List(), 0, 0, 0);
+ return results;
+ }
+ private void Search(IList state, int left, int right, int vertical)
+ {
+ if (state.Count == n)
+ {
+ Print(state);
+ return;
+ }
+ int available = ~(left | right | vertical) & ((1 << n) - 1);
+ while (available != 0)
+ {
+ int x = available & -available;
+ state.Add(x);
+ Search(state, (left | x ) << 1, (right | x ) >> 1, vertical | x);
+ state.RemoveAt(state.Count - 1);
+ available &= ~x;
+ }
+ }
+
+ private void Print(IList state)
+ {
+ var result = new List();
+ var sb = new StringBuilder(n);
+ foreach (var s in state)
+ {
+ var x = s;
+ for (var i = 0; i < n; ++i)
+ {
+ sb.Append((x & 1) != 0 ? 'Q': '.');
+ x >>= 1;
+ }
+ result.Add(sb.ToString());
+ sb.Clear();
+ }
+ results.Add(result);
+ }
+}
```
+
+
diff --git a/lcci/08.12.Eight Queens/README_EN.md b/lcci/08.12.Eight Queens/README_EN.md
index 17a3ecb3e6b9a..d01fa078902a0 100644
--- a/lcci/08.12.Eight Queens/README_EN.md
+++ b/lcci/08.12.Eight Queens/README_EN.md
@@ -44,12 +44,10 @@
## Solutions
-DFS.
+### Solution 1
-### **Python3**
-
```python
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
@@ -75,8 +73,6 @@ class Solution:
return res
```
-### **Java**
-
```java
class Solution {
public List> solveNQueens(int n) {
@@ -87,9 +83,13 @@ class Solution {
Arrays.fill(t, ".");
g[i] = t;
}
+ // 列是否已经有值
boolean[] col = new boolean[n];
+ // 斜线是否已经有值
boolean[] dg = new boolean[2 * n];
+ // 反斜线是否已经有值
boolean[] udg = new boolean[2 * n];
+ // 从第一行开始搜索
dfs(0, n, col, dg, udg, g, res);
return res;
}
@@ -117,8 +117,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -150,8 +148,6 @@ public:
};
```
-### **Go**
-
```go
func solveNQueens(n int) [][]string {
res := [][]string{}
@@ -190,10 +186,58 @@ func dfs(u, n int, col, dg, udg []bool, g [][]string, res *[][]string) {
}
```
-### **...**
+```cs
+using System.Collections.Generic;
+using System.Text;
-```
+public class Solution {
+ private IList> results = new List>();
+ private int n;
+ public IList> SolveNQueens(int n) {
+ this.n = n;
+ Search(new List(), 0, 0, 0);
+ return results;
+ }
+
+ private void Search(IList state, int left, int right, int vertical)
+ {
+ if (state.Count == n)
+ {
+ Print(state);
+ return;
+ }
+ int available = ~(left | right | vertical) & ((1 << n) - 1);
+ while (available != 0)
+ {
+ int x = available & -available;
+ state.Add(x);
+ Search(state, (left | x ) << 1, (right | x ) >> 1, vertical | x);
+ state.RemoveAt(state.Count - 1);
+ available &= ~x;
+ }
+ }
+
+ private void Print(IList state)
+ {
+ var result = new List();
+ var sb = new StringBuilder(n);
+ foreach (var s in state)
+ {
+ var x = s;
+ for (var i = 0; i < n; ++i)
+ {
+ sb.Append((x & 1) != 0 ? 'Q': '.');
+ x >>= 1;
+ }
+ result.Add(sb.ToString());
+ sb.Clear();
+ }
+ results.Add(result);
+ }
+}
```
+
+
diff --git a/lcci/08.13.Pile Box/README.md b/lcci/08.13.Pile Box/README.md
index e253a86c3558e..97208cc3c71f6 100644
--- a/lcci/08.13.Pile Box/README.md
+++ b/lcci/08.13.Pile Box/README.md
@@ -23,9 +23,7 @@
## 解法
-
-
-**方法一:排序 + 动态规划**
+### 方法一:排序 + 动态规划
我们先将箱子按照宽度升序、深度降序的顺序进行排序,然后使用动态规划求解。
@@ -37,10 +35,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def pileBox(self, box: List[List[int]]) -> int:
@@ -55,10 +49,6 @@ class Solution:
return max(f)
```
-### **Java**
-
-
-
```java
class Solution {
public int pileBox(int[][] box) {
@@ -80,8 +70,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -105,8 +93,6 @@ public:
};
```
-### **Go**
-
```go
func pileBox(box [][]int) int {
sort.Slice(box, func(i, j int) bool {
@@ -127,8 +113,6 @@ func pileBox(box [][]int) int {
}
```
-### **TypeScript**
-
```ts
function pileBox(box: number[][]): number {
box.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]));
@@ -148,10 +132,6 @@ function pileBox(box: number[][]): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.13.Pile Box/README_EN.md b/lcci/08.13.Pile Box/README_EN.md
index 4e69a2b85fd75..dd4b2fc280f5a 100644
--- a/lcci/08.13.Pile Box/README_EN.md
+++ b/lcci/08.13.Pile Box/README_EN.md
@@ -29,7 +29,7 @@
## Solutions
-**Solution 1: Sorting + Dynamic Programming**
+### Solution 1: Sorting + Dynamic Programming
First, we sort the boxes in ascending order by width and descending order by depth, then use dynamic programming to solve the problem.
@@ -41,8 +41,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i
-### **Python3**
-
```python
class Solution:
def pileBox(self, box: List[List[int]]) -> int:
@@ -57,8 +55,6 @@ class Solution:
return max(f)
```
-### **Java**
-
```java
class Solution {
public int pileBox(int[][] box) {
@@ -80,8 +76,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -105,8 +99,6 @@ public:
};
```
-### **Go**
-
```go
func pileBox(box [][]int) int {
sort.Slice(box, func(i, j int) bool {
@@ -127,8 +119,6 @@ func pileBox(box [][]int) int {
}
```
-### **TypeScript**
-
```ts
function pileBox(box: number[][]): number {
box.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]));
@@ -148,10 +138,6 @@ function pileBox(box: number[][]): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.14.Boolean Evaluation/README.md b/lcci/08.14.Boolean Evaluation/README.md
index f8ecc84d0ffdd..68e3711020cf1 100644
--- a/lcci/08.14.Boolean Evaluation/README.md
+++ b/lcci/08.14.Boolean Evaluation/README.md
@@ -31,16 +31,10 @@
## 解法
-
-
-**方法一:记忆化搜索**
+### 方法一:记忆化搜索
-### **Python3**
-
-
-
```python
class Solution:
def countEval(self, s: str, result: int) -> int:
@@ -68,10 +62,6 @@ class Solution:
return ans[result] if 0 <= result < 2 else 0
```
-### **Java**
-
-
-
```java
class Solution {
private Map memo;
@@ -117,8 +107,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -159,8 +147,6 @@ public:
};
```
-### **Go**
-
```go
func countEval(s string, result int) int {
memo := map[string][]int{}
@@ -204,10 +190,6 @@ func countEval(s string, result int) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/08.14.Boolean Evaluation/README_EN.md b/lcci/08.14.Boolean Evaluation/README_EN.md
index 6549ad6ce0db5..3473013ea8f85 100644
--- a/lcci/08.14.Boolean Evaluation/README_EN.md
+++ b/lcci/08.14.Boolean Evaluation/README_EN.md
@@ -42,9 +42,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -73,8 +73,6 @@ class Solution:
return ans[result] if 0 <= result < 2 else 0
```
-### **Java**
-
```java
class Solution {
private Map memo;
@@ -120,8 +118,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -162,8 +158,6 @@ public:
};
```
-### **Go**
-
```go
func countEval(s string, result int) int {
memo := map[string][]int{}
@@ -207,10 +201,6 @@ func countEval(s string, result int) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.01.Sorted Merge/README.md b/lcci/10.01.Sorted Merge/README.md
index b967d31f6feb5..6707438a1945d 100644
--- a/lcci/10.01.Sorted Merge/README.md
+++ b/lcci/10.01.Sorted Merge/README.md
@@ -25,14 +25,10 @@ B = [2,5,6], n = 3
## 解法
-
+### 方法一
-### **Python3**
-
-
-
```python
class Solution:
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
@@ -49,10 +45,6 @@ class Solution:
j -= 1
```
-### **Java**
-
-
-
```java
class Solution {
public void merge(int[] A, int m, int[] B, int n) {
@@ -68,33 +60,35 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number[]} A
- * @param {number} m
- * @param {number[]} B
- * @param {number} n
- * @return {void} Do not return anything, modify A in-place instead.
- */
-var merge = function (A, m, B, n) {
- let i = m - 1,
- j = n - 1;
- for (let k = A.length - 1; k >= 0; k--) {
- if (k == i) return;
- if (i < 0 || A[i] <= B[j]) {
- A[k] = B[j];
- j--;
- } else {
- A[k] = A[i];
- i--;
+```cpp
+class Solution {
+public:
+ void merge(vector& A, int m, vector& B, int n) {
+ int i = m - 1, j = n - 1;
+ for (int k = A.size() - 1; k >= 0; --k) {
+ if (j < 0 || (i >= 0 && A[i] >= B[j]))
+ A[k] = A[i--];
+ else
+ A[k] = B[j--];
}
}
};
```
-### **TypeScript**
+```go
+func merge(A []int, m int, B []int, n int) {
+ i, j := m-1, n-1
+ for k := len(A) - 1; k >= 0; k-- {
+ if j < 0 || (i >= 0 && A[i] >= B[j]) {
+ A[k] = A[i]
+ i--
+ } else {
+ A[k] = B[j]
+ j--
+ }
+ }
+}
+```
```ts
/**
@@ -115,8 +109,6 @@ function merge(A: number[], m: number, B: number[], n: number): void {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn merge(a: &mut Vec, m: i32, b: &mut Vec, n: i32) {
@@ -137,44 +129,30 @@ impl Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- void merge(vector& A, int m, vector& B, int n) {
- int i = m - 1, j = n - 1;
- for (int k = A.size() - 1; k >= 0; --k) {
- if (j < 0 || (i >= 0 && A[i] >= B[j]))
- A[k] = A[i--];
- else
- A[k] = B[j--];
+```js
+/**
+ * @param {number[]} A
+ * @param {number} m
+ * @param {number[]} B
+ * @param {number} n
+ * @return {void} Do not return anything, modify A in-place instead.
+ */
+var merge = function (A, m, B, n) {
+ let i = m - 1,
+ j = n - 1;
+ for (let k = A.length - 1; k >= 0; k--) {
+ if (k == i) return;
+ if (i < 0 || A[i] <= B[j]) {
+ A[k] = B[j];
+ j--;
+ } else {
+ A[k] = A[i];
+ i--;
}
}
};
```
-### **Go**
-
-```go
-func merge(A []int, m int, B []int, n int) {
- i, j := m-1, n-1
- for k := len(A) - 1; k >= 0; k-- {
- if j < 0 || (i >= 0 && A[i] >= B[j]) {
- A[k] = A[i]
- i--
- } else {
- A[k] = B[j]
- j--
- }
- }
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.01.Sorted Merge/README_EN.md b/lcci/10.01.Sorted Merge/README_EN.md
index d3aa59e6abb4f..716baf5ced6cd 100644
--- a/lcci/10.01.Sorted Merge/README_EN.md
+++ b/lcci/10.01.Sorted Merge/README_EN.md
@@ -24,9 +24,9 @@ B = [2,5,6], n = 3
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -44,8 +44,6 @@ class Solution:
j -= 1
```
-### **Java**
-
```java
class Solution {
public void merge(int[] A, int m, int[] B, int n) {
@@ -61,33 +59,35 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number[]} A
- * @param {number} m
- * @param {number[]} B
- * @param {number} n
- * @return {void} Do not return anything, modify A in-place instead.
- */
-var merge = function (A, m, B, n) {
- let i = m - 1,
- j = n - 1;
- for (let k = A.length - 1; k >= 0; k--) {
- if (k == i) return;
- if (i < 0 || A[i] <= B[j]) {
- A[k] = B[j];
- j--;
- } else {
- A[k] = A[i];
- i--;
+```cpp
+class Solution {
+public:
+ void merge(vector& A, int m, vector& B, int n) {
+ int i = m - 1, j = n - 1;
+ for (int k = A.size() - 1; k >= 0; --k) {
+ if (j < 0 || (i >= 0 && A[i] >= B[j]))
+ A[k] = A[i--];
+ else
+ A[k] = B[j--];
}
}
};
```
-### **TypeScript**
+```go
+func merge(A []int, m int, B []int, n int) {
+ i, j := m-1, n-1
+ for k := len(A) - 1; k >= 0; k-- {
+ if j < 0 || (i >= 0 && A[i] >= B[j]) {
+ A[k] = A[i]
+ i--
+ } else {
+ A[k] = B[j]
+ j--
+ }
+ }
+}
+```
```ts
/**
@@ -108,8 +108,6 @@ function merge(A: number[], m: number, B: number[], n: number): void {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn merge(a: &mut Vec, m: i32, b: &mut Vec, n: i32) {
@@ -130,44 +128,30 @@ impl Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- void merge(vector& A, int m, vector& B, int n) {
- int i = m - 1, j = n - 1;
- for (int k = A.size() - 1; k >= 0; --k) {
- if (j < 0 || (i >= 0 && A[i] >= B[j]))
- A[k] = A[i--];
- else
- A[k] = B[j--];
+```js
+/**
+ * @param {number[]} A
+ * @param {number} m
+ * @param {number[]} B
+ * @param {number} n
+ * @return {void} Do not return anything, modify A in-place instead.
+ */
+var merge = function (A, m, B, n) {
+ let i = m - 1,
+ j = n - 1;
+ for (let k = A.length - 1; k >= 0; k--) {
+ if (k == i) return;
+ if (i < 0 || A[i] <= B[j]) {
+ A[k] = B[j];
+ j--;
+ } else {
+ A[k] = A[i];
+ i--;
}
}
};
```
-### **Go**
-
-```go
-func merge(A []int, m int, B []int, n int) {
- i, j := m-1, n-1
- for k := len(A) - 1; k >= 0; k-- {
- if j < 0 || (i >= 0 && A[i] >= B[j]) {
- A[k] = A[i]
- i--
- } else {
- A[k] = B[j]
- j--
- }
- }
-}
-```
-
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.02.Group Anagrams/README.md b/lcci/10.02.Group Anagrams/README.md
index ddebbb79b0dc3..0fd6f1e5e06a9 100644
--- a/lcci/10.02.Group Anagrams/README.md
+++ b/lcci/10.02.Group Anagrams/README.md
@@ -28,24 +28,10 @@
## 解法
-
-
-遍历字符串,将每个字符串按照字符字典序排序后得到一个新的字符串,将相同的新字符串放在哈希表的同一个 key 对应 value 列表中。
-
-| key | value |
-| ------- | ----------------------- |
-| `"aet"` | `["eat", "tea", "ate"]` |
-| `"ant"` | `["tan", "nat"] ` |
-| `"abt"` | `["bat"] ` |
-
-最后返回哈希表的 value 列表即可。
+### 方法一
-### **Python3**
-
-
-
```python
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
@@ -56,10 +42,6 @@ class Solution:
return list(chars.values())
```
-### **Java**
-
-
-
```java
class Solution {
public List> groupAnagrams(String[] strs) {
@@ -75,8 +57,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -96,8 +76,6 @@ public:
};
```
-### **Go**
-
```go
func groupAnagrams(strs []string) [][]string {
chars := map[string][]string{}
@@ -116,8 +94,6 @@ func groupAnagrams(strs []string) [][]string {
}
```
-### **TypeScript**
-
```ts
function groupAnagrams(strs: string[]): string[][] {
const map = new Map();
@@ -129,8 +105,6 @@ function groupAnagrams(strs: string[]): string[][] {
}
```
-### **Rust**
-
```rust
use std::collections::HashMap;
@@ -152,10 +126,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.02.Group Anagrams/README_EN.md b/lcci/10.02.Group Anagrams/README_EN.md
index 6c4aa02bce865..9569e8848eef1 100644
--- a/lcci/10.02.Group Anagrams/README_EN.md
+++ b/lcci/10.02.Group Anagrams/README_EN.md
@@ -35,16 +35,10 @@
## Solutions
-| key | value |
-| ------- | ----------------------- |
-| `"aet"` | `["eat", "tea", "ate"]` |
-| `"ant"` | `["tan", "nat"] ` |
-| `"abt"` | `["bat"] ` |
+### Solution 1
-### **Python3**
-
```python
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
@@ -55,8 +49,6 @@ class Solution:
return list(chars.values())
```
-### **Java**
-
```java
class Solution {
public List> groupAnagrams(String[] strs) {
@@ -72,8 +64,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -93,8 +83,6 @@ public:
};
```
-### **Go**
-
```go
func groupAnagrams(strs []string) [][]string {
chars := map[string][]string{}
@@ -113,8 +101,6 @@ func groupAnagrams(strs []string) [][]string {
}
```
-### **TypeScript**
-
```ts
function groupAnagrams(strs: string[]): string[][] {
const map = new Map();
@@ -126,8 +112,6 @@ function groupAnagrams(strs: string[]): string[][] {
}
```
-### **Rust**
-
```rust
use std::collections::HashMap;
@@ -149,10 +133,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.03.Search Rotate Array/README.md b/lcci/10.03.Search Rotate Array/README.md
index 0209693b13f13..8356baf6d54ec 100644
--- a/lcci/10.03.Search Rotate Array/README.md
+++ b/lcci/10.03.Search Rotate Array/README.md
@@ -22,9 +22,7 @@
## 解法
-
-
-**方法一:二分查找**
+### 方法一:二分查找
我们定义二分查找的左边界 $l=0$,右边界 $r=n-1$,其中 $n$ 为数组的长度。
@@ -46,10 +44,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def search(self, arr: List[int], target: int) -> int:
@@ -73,10 +67,6 @@ class Solution:
return l if arr[l] == target else -1
```
-### **Java**
-
-
-
```java
class Solution {
public int search(int[] arr, int target) {
@@ -107,8 +97,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -140,8 +128,6 @@ public:
};
```
-### **Go**
-
```go
func search(arr []int, target int) int {
l, r := 0, len(arr)-1
@@ -173,8 +159,6 @@ func search(arr []int, target int) int {
}
```
-### **TypeScript**
-
```ts
function search(arr: number[], target: number): number {
let [l, r] = [0, arr.length - 1];
@@ -203,10 +187,6 @@ function search(arr: number[], target: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.03.Search Rotate Array/README_EN.md b/lcci/10.03.Search Rotate Array/README_EN.md
index e295f94c36cf8..bf1dcafd5bda5 100644
--- a/lcci/10.03.Search Rotate Array/README_EN.md
+++ b/lcci/10.03.Search Rotate Array/README_EN.md
@@ -28,7 +28,7 @@
## Solutions
-**Solution 1: Binary Search**
+### Solution 1: Binary Search
We define the left boundary of the binary search as $l=0$ and the right boundary as $r=n-1$, where $n$ is the length of the array.
@@ -50,8 +50,6 @@ Similar problems:
-### **Python3**
-
```python
class Solution:
def search(self, arr: List[int], target: int) -> int:
@@ -75,8 +73,6 @@ class Solution:
return l if arr[l] == target else -1
```
-### **Java**
-
```java
class Solution {
public int search(int[] arr, int target) {
@@ -107,8 +103,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -140,8 +134,6 @@ public:
};
```
-### **Go**
-
```go
func search(arr []int, target int) int {
l, r := 0, len(arr)-1
@@ -173,8 +165,6 @@ func search(arr []int, target int) int {
}
```
-### **TypeScript**
-
```ts
function search(arr: number[], target: number): number {
let [l, r] = [0, arr.length - 1];
@@ -203,10 +193,6 @@ function search(arr: number[], target: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.05.Sparse Array Search/README.md b/lcci/10.05.Sparse Array Search/README.md
index e2fe64bce8236..df890703ef4b6 100644
--- a/lcci/10.05.Sparse Array Search/README.md
+++ b/lcci/10.05.Sparse Array Search/README.md
@@ -28,14 +28,10 @@
## 解法
-
+### 方法一
-### **Python3**
-
-
-
```python
class Solution:
def findString(self, words: List[str], s: str) -> int:
@@ -51,10 +47,6 @@ class Solution:
return -1 if words[left] != s else left
```
-### **Java**
-
-
-
```java
class Solution {
public int findString(String[] words, String s) {
@@ -75,8 +67,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -95,8 +85,6 @@ public:
};
```
-### **Go**
-
```go
func findString(words []string, s string) int {
left, right := 0, len(words)-1
@@ -118,10 +106,6 @@ func findString(words []string, s string) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.05.Sparse Array Search/README_EN.md b/lcci/10.05.Sparse Array Search/README_EN.md
index f68b4eea7da6d..d02390b80bb35 100644
--- a/lcci/10.05.Sparse Array Search/README_EN.md
+++ b/lcci/10.05.Sparse Array Search/README_EN.md
@@ -34,9 +34,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -53,8 +53,6 @@ class Solution:
return -1 if words[left] != s else left
```
-### **Java**
-
```java
class Solution {
public int findString(String[] words, String s) {
@@ -75,8 +73,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -95,8 +91,6 @@ public:
};
```
-### **Go**
-
```go
func findString(words []string, s string) int {
left, right := 0, len(words)-1
@@ -118,10 +112,6 @@ func findString(words []string, s string) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.09.Sorted Matrix Search/README.md b/lcci/10.09.Sorted Matrix Search/README.md
index 07fadeeb2afff..a34fee2ece5f6 100644
--- a/lcci/10.09.Sorted Matrix Search/README.md
+++ b/lcci/10.09.Sorted Matrix Search/README.md
@@ -26,16 +26,10 @@
## 解法
-
-
-从左下角(或右上角)开始查找即可。
+### 方法一
-### **Python3**
-
-
-
```python
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
@@ -53,10 +47,6 @@ class Solution:
return False
```
-### **Java**
-
-
-
```java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
@@ -80,8 +70,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -101,8 +89,6 @@ public:
};
```
-### **Go**
-
```go
func searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 || len(matrix[0]) == 0 {
@@ -124,10 +110,6 @@ func searchMatrix(matrix [][]int, target int) bool {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.09.Sorted Matrix Search/README_EN.md b/lcci/10.09.Sorted Matrix Search/README_EN.md
index be59a60b499d3..87b7d3f3407eb 100644
--- a/lcci/10.09.Sorted Matrix Search/README_EN.md
+++ b/lcci/10.09.Sorted Matrix Search/README_EN.md
@@ -34,9 +34,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -55,8 +55,6 @@ class Solution:
return False
```
-### **Java**
-
```java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
@@ -80,8 +78,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -101,8 +97,6 @@ public:
};
```
-### **Go**
-
```go
func searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 || len(matrix[0]) == 0 {
@@ -124,10 +118,6 @@ func searchMatrix(matrix [][]int, target int) bool {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.10.Rank from Stream/README.md b/lcci/10.10.Rank from Stream/README.md
index a5223abe9d0a2..9387bd16a8967 100644
--- a/lcci/10.10.Rank from Stream/README.md
+++ b/lcci/10.10.Rank from Stream/README.md
@@ -31,9 +31,7 @@
## 解法
-
-
-**方法一:树状数组**
+### 方法一:树状数组
树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作:
@@ -50,10 +48,6 @@
-### **Python3**
-
-
-
```python
class BinaryIndexedTree:
def __init__(self, n):
@@ -94,10 +88,6 @@ class StreamRank:
# param_2 = obj.getRankOfNumber(x)
```
-### **Java**
-
-
-
```java
class BinaryIndexedTree {
private int n;
@@ -153,8 +143,6 @@ class StreamRank {
*/
```
-### **C++**
-
```cpp
class BinaryIndexedTree {
public:
@@ -211,8 +199,6 @@ public:
*/
```
-### **Go**
-
```go
type BinaryIndexedTree struct {
n int
@@ -269,10 +255,6 @@ func (this *StreamRank) GetRankOfNumber(x int) int {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.10.Rank from Stream/README_EN.md b/lcci/10.10.Rank from Stream/README_EN.md
index e092d8e228a30..1fba5cc1116b9 100644
--- a/lcci/10.10.Rank from Stream/README_EN.md
+++ b/lcci/10.10.Rank from Stream/README_EN.md
@@ -33,12 +33,10 @@
## Solutions
-Binary Indexed Tree.
+### Solution 1
-### **Python3**
-
```python
class BinaryIndexedTree:
def __init__(self, n):
@@ -79,8 +77,6 @@ class StreamRank:
# param_2 = obj.getRankOfNumber(x)
```
-### **Java**
-
```java
class BinaryIndexedTree {
private int n;
@@ -136,8 +132,6 @@ class StreamRank {
*/
```
-### **C++**
-
```cpp
class BinaryIndexedTree {
public:
@@ -194,8 +188,6 @@ public:
*/
```
-### **Go**
-
```go
type BinaryIndexedTree struct {
n int
@@ -252,10 +244,6 @@ func (this *StreamRank) GetRankOfNumber(x int) int {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.11.Peaks and Valleys/README.md b/lcci/10.11.Peaks and Valleys/README.md
index 6ff4de85ce1c8..9f3aaf7cfd4eb 100644
--- a/lcci/10.11.Peaks and Valleys/README.md
+++ b/lcci/10.11.Peaks and Valleys/README.md
@@ -17,9 +17,7 @@
## 解法
-
-
-**方法一:排序**
+### 方法一:排序
我们先对数组进行排序,然后遍历数组,将偶数下标的元素与后一个元素交换即可。
@@ -27,10 +25,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
@@ -39,10 +33,6 @@ class Solution:
nums[i : i + 2] = nums[i : i + 2][::-1]
```
-### **Java**
-
-
-
```java
class Solution {
public void wiggleSort(int[] nums) {
@@ -57,8 +47,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -72,8 +60,6 @@ public:
};
```
-### **Go**
-
```go
func wiggleSort(nums []int) {
sort.Ints(nums)
@@ -83,8 +69,6 @@ func wiggleSort(nums []int) {
}
```
-### **TypeScript**
-
```ts
/**
Do not return anything, modify nums in-place instead.
@@ -98,10 +82,6 @@ function wiggleSort(nums: number[]): void {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/10.11.Peaks and Valleys/README_EN.md b/lcci/10.11.Peaks and Valleys/README_EN.md
index f02231607335e..565ea89c2798a 100644
--- a/lcci/10.11.Peaks and Valleys/README_EN.md
+++ b/lcci/10.11.Peaks and Valleys/README_EN.md
@@ -20,7 +20,7 @@
## Solutions
-**Solution 1: Sorting**
+### Solution 1: Sorting
We first sort the array, and then traverse the array and swap the elements at even indices with their next element.
@@ -28,8 +28,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log
-### **Python3**
-
```python
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
@@ -38,8 +36,6 @@ class Solution:
nums[i : i + 2] = nums[i : i + 2][::-1]
```
-### **Java**
-
```java
class Solution {
public void wiggleSort(int[] nums) {
@@ -54,8 +50,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -69,8 +63,6 @@ public:
};
```
-### **Go**
-
```go
func wiggleSort(nums []int) {
sort.Ints(nums)
@@ -80,8 +72,6 @@ func wiggleSort(nums []int) {
}
```
-### **TypeScript**
-
```ts
/**
Do not return anything, modify nums in-place instead.
@@ -95,10 +85,6 @@ function wiggleSort(nums: number[]): void {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.01.Swap Numbers/README.md b/lcci/16.01.Swap Numbers/README.md
index 0dd5cc45598d5..a87da3b984dc4 100644
--- a/lcci/16.01.Swap Numbers/README.md
+++ b/lcci/16.01.Swap Numbers/README.md
@@ -17,9 +17,7 @@
## 解法
-
-
-**方法一:位运算**
+### 方法一:位运算
我们可以使用异或运算 $\oplus$ 来实现两个数的交换。
@@ -41,10 +39,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def swapNumbers(self, numbers: List[int]) -> List[int]:
@@ -54,10 +48,6 @@ class Solution:
return numbers
```
-### **Java**
-
-
-
```java
class Solution {
public int[] swapNumbers(int[] numbers) {
@@ -69,26 +59,6 @@ class Solution {
}
```
-### **TypeScript**
-
-```ts
-function swapNumbers(numbers: number[]): number[] {
- numbers[0] ^= numbers[1];
- numbers[1] ^= numbers[0];
- numbers[0] ^= numbers[1];
- return numbers;
-}
-```
-
-```ts
-function swapNumbers(numbers: number[]): number[] {
- [numbers[0], numbers[1]] = [numbers[1], numbers[0]];
- return numbers;
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -101,8 +71,6 @@ public:
};
```
-### **Go**
-
```go
func swapNumbers(numbers []int) []int {
numbers[0] ^= numbers[1]
@@ -112,10 +80,28 @@ func swapNumbers(numbers []int) []int {
}
```
-### **...**
-
+```ts
+function swapNumbers(numbers: number[]): number[] {
+ numbers[0] ^= numbers[1];
+ numbers[1] ^= numbers[0];
+ numbers[0] ^= numbers[1];
+ return numbers;
+}
```
+
+
+### 方法二
+
+
+
+```ts
+function swapNumbers(numbers: number[]): number[] {
+ [numbers[0], numbers[1]] = [numbers[1], numbers[0]];
+ return numbers;
+}
```
+
+
diff --git a/lcci/16.01.Swap Numbers/README_EN.md b/lcci/16.01.Swap Numbers/README_EN.md
index bf8df6356de4b..6649549ef0226 100644
--- a/lcci/16.01.Swap Numbers/README_EN.md
+++ b/lcci/16.01.Swap Numbers/README_EN.md
@@ -24,7 +24,7 @@
## Solutions
-**Solution 1: Bitwise Operation**
+### Solution 1: Bitwise Operation
We can use the XOR operation $\oplus$ to implement the swap of two numbers.
@@ -46,8 +46,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$.
-### **Python3**
-
```python
class Solution:
def swapNumbers(self, numbers: List[int]) -> List[int]:
@@ -57,8 +55,6 @@ class Solution:
return numbers
```
-### **Java**
-
```java
class Solution {
public int[] swapNumbers(int[] numbers) {
@@ -70,19 +66,6 @@ class Solution {
}
```
-## **TypeScript**
-
-```ts
-function swapNumbers(numbers: number[]): number[] {
- numbers[0] ^= numbers[1];
- numbers[1] ^= numbers[0];
- numbers[0] ^= numbers[1];
- return numbers;
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -95,8 +78,6 @@ public:
};
```
-### **Go**
-
```go
func swapNumbers(numbers []int) []int {
numbers[0] ^= numbers[1]
@@ -106,10 +87,28 @@ func swapNumbers(numbers []int) []int {
}
```
-### **...**
-
+```ts
+function swapNumbers(numbers: number[]): number[] {
+ numbers[0] ^= numbers[1];
+ numbers[1] ^= numbers[0];
+ numbers[0] ^= numbers[1];
+ return numbers;
+}
```
+
+
+### Solution 2
+
+
+
+```ts
+function swapNumbers(numbers: number[]): number[] {
+ [numbers[0], numbers[1]] = [numbers[1], numbers[0]];
+ return numbers;
+}
```
+
+
diff --git a/lcci/16.02.Words Frequency/README.md b/lcci/16.02.Words Frequency/README.md
index 51328dcea8eaa..b27886435d3b9 100644
--- a/lcci/16.02.Words Frequency/README.md
+++ b/lcci/16.02.Words Frequency/README.md
@@ -30,9 +30,7 @@ wordsFrequency.get("pen"); //返回1
## 解法
-
-
-**方法一:哈希表**
+### 方法一:哈希表
我们用哈希表 $cnt$ 统计 $book$ 中每个单词出现的次数。
@@ -42,10 +40,6 @@ wordsFrequency.get("pen"); //返回1
-### **Python3**
-
-
-
```python
class WordsFrequency:
def __init__(self, book: List[str]):
@@ -60,10 +54,6 @@ class WordsFrequency:
# param_1 = obj.get(word)
```
-### **Java**
-
-
-
```java
class WordsFrequency {
private Map cnt = new HashMap<>();
@@ -86,8 +76,6 @@ class WordsFrequency {
*/
```
-### **C++**
-
```cpp
class WordsFrequency {
public:
@@ -112,8 +100,6 @@ private:
*/
```
-### **Go**
-
```go
type WordsFrequency struct {
cnt map[string]int
@@ -138,36 +124,6 @@ func (this *WordsFrequency) Get(word string) int {
*/
```
-### **JavaScript**
-
-```js
-/**
- * @param {string[]} book
- */
-var WordsFrequency = function (book) {
- this.cnt = new Map();
- for (const x of book) {
- this.cnt.set(x, (this.cnt.get(x) || 0) + 1);
- }
-};
-
-/**
- * @param {string} word
- * @return {number}
- */
-WordsFrequency.prototype.get = function (word) {
- return this.cnt.get(word) || 0;
-};
-
-/**
- * Your WordsFrequency object will be instantiated and called as such:
- * var obj = new WordsFrequency(book)
- * var param_1 = obj.get(word)
- */
-```
-
-### **TypeScript**
-
```ts
class WordsFrequency {
private cnt: Map;
@@ -192,8 +148,6 @@ class WordsFrequency {
*/
```
-### **Rust**
-
```rust
use std::collections::HashMap;
struct WordsFrequency {
@@ -223,10 +177,32 @@ impl WordsFrequency {
*/
```
-### **...**
+```js
+/**
+ * @param {string[]} book
+ */
+var WordsFrequency = function (book) {
+ this.cnt = new Map();
+ for (const x of book) {
+ this.cnt.set(x, (this.cnt.get(x) || 0) + 1);
+ }
+};
-```
+/**
+ * @param {string} word
+ * @return {number}
+ */
+WordsFrequency.prototype.get = function (word) {
+ return this.cnt.get(word) || 0;
+};
+/**
+ * Your WordsFrequency object will be instantiated and called as such:
+ * var obj = new WordsFrequency(book)
+ * var param_1 = obj.get(word)
+ */
```
+
+
diff --git a/lcci/16.02.Words Frequency/README_EN.md b/lcci/16.02.Words Frequency/README_EN.md
index b40a13ee08478..efae82c6c72ef 100644
--- a/lcci/16.02.Words Frequency/README_EN.md
+++ b/lcci/16.02.Words Frequency/README_EN.md
@@ -42,7 +42,7 @@ wordsFrequency.get("pen"); //returns 1
## Solutions
-**Solution 1: Hash Table**
+### Solution 1: Hash Table
We use a hash table $cnt$ to count the number of occurrences of each word in $book$.
@@ -52,8 +52,6 @@ In terms of time complexity, the time complexity of initializing the hash table
-### **Python3**
-
```python
class WordsFrequency:
def __init__(self, book: List[str]):
@@ -68,8 +66,6 @@ class WordsFrequency:
# param_1 = obj.get(word)
```
-### **Java**
-
```java
class WordsFrequency {
private Map cnt = new HashMap<>();
@@ -92,8 +88,6 @@ class WordsFrequency {
*/
```
-### **C++**
-
```cpp
class WordsFrequency {
public:
@@ -118,8 +112,6 @@ private:
*/
```
-### **Go**
-
```go
type WordsFrequency struct {
cnt map[string]int
@@ -144,36 +136,6 @@ func (this *WordsFrequency) Get(word string) int {
*/
```
-### **JavaScript**
-
-```js
-/**
- * @param {string[]} book
- */
-var WordsFrequency = function (book) {
- this.cnt = new Map();
- for (const x of book) {
- this.cnt.set(x, (this.cnt.get(x) || 0) + 1);
- }
-};
-
-/**
- * @param {string} word
- * @return {number}
- */
-WordsFrequency.prototype.get = function (word) {
- return this.cnt.get(word) || 0;
-};
-
-/**
- * Your WordsFrequency object will be instantiated and called as such:
- * var obj = new WordsFrequency(book)
- * var param_1 = obj.get(word)
- */
-```
-
-### **TypeScript**
-
```ts
class WordsFrequency {
private cnt: Map;
@@ -198,8 +160,6 @@ class WordsFrequency {
*/
```
-### **Rust**
-
```rust
use std::collections::HashMap;
struct WordsFrequency {
@@ -229,10 +189,32 @@ impl WordsFrequency {
*/
```
-### **...**
+```js
+/**
+ * @param {string[]} book
+ */
+var WordsFrequency = function (book) {
+ this.cnt = new Map();
+ for (const x of book) {
+ this.cnt.set(x, (this.cnt.get(x) || 0) + 1);
+ }
+};
-```
+/**
+ * @param {string} word
+ * @return {number}
+ */
+WordsFrequency.prototype.get = function (word) {
+ return this.cnt.get(word) || 0;
+};
+/**
+ * Your WordsFrequency object will be instantiated and called as such:
+ * var obj = new WordsFrequency(book)
+ * var param_1 = obj.get(word)
+ */
```
+
+
diff --git a/lcci/16.03.Intersection/README.md b/lcci/16.03.Intersection/README.md
index 673f61b2a8743..3235268add9d2 100644
--- a/lcci/16.03.Intersection/README.md
+++ b/lcci/16.03.Intersection/README.md
@@ -33,29 +33,4 @@ line2 = {1, 0}, {2, 1}
## 解法
-
-
-
-### **Python3**
-
-
-
-```python
-
-```
-
-### **Java**
-
-
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/16.03.Intersection/README_EN.md b/lcci/16.03.Intersection/README_EN.md
index a49f3ad360aea..56beb12b293e7 100644
--- a/lcci/16.03.Intersection/README_EN.md
+++ b/lcci/16.03.Intersection/README_EN.md
@@ -50,24 +50,4 @@ line2 = {1, 0}, {2, 1}
## Solutions
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/16.04.Tic-Tac-Toe/README.md b/lcci/16.04.Tic-Tac-Toe/README.md
index b8e03430eb2c5..3090e6c45a037 100644
--- a/lcci/16.04.Tic-Tac-Toe/README.md
+++ b/lcci/16.04.Tic-Tac-Toe/README.md
@@ -39,9 +39,7 @@
## 解法
-
-
-**方法一:计数**
+### 方法一:计数
对于每个格子,如果是 `X`,我们不妨将计数加 $1$,如果是 `O`,我们不妨将计数减 $1$。那么当某个格子所在的行、列或者对角线的计数的绝对值等于 $n$ 时,说明当前玩家在该行、列或者对角线上放置了 $n$ 个相同字符,游戏结束,返回对应的字符即可。
@@ -53,10 +51,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def tictactoe(self, board: List[str]) -> str:
@@ -87,10 +81,6 @@ class Solution:
return 'Pending' if has_empty_grid else 'Draw'
```
-### **Java**
-
-
-
```java
class Solution {
public String tictactoe(String[] board) {
@@ -126,8 +116,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -162,8 +150,6 @@ public:
};
```
-### **Go**
-
```go
func tictactoe(board []string) string {
n := len(board)
@@ -208,8 +194,6 @@ func abs(x int) int {
}
```
-### **TypeScript**
-
```ts
function tictactoe(board: string[]): string {
const n = board.length;
@@ -247,10 +231,6 @@ function tictactoe(board: string[]): string {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.04.Tic-Tac-Toe/README_EN.md b/lcci/16.04.Tic-Tac-Toe/README_EN.md
index cc5a604512939..eb7f46f4edabd 100644
--- a/lcci/16.04.Tic-Tac-Toe/README_EN.md
+++ b/lcci/16.04.Tic-Tac-Toe/README_EN.md
@@ -51,7 +51,7 @@
## Solutions
-**Solution 1: Counting**
+### Solution 1: Counting
For each cell, if it is `X`, we can add $1$ to the count; if it is `O`, we can subtract $1$ from the count. When the absolute value of the count of a row, column, or diagonal equals $n$, it means that the current player has placed $n$ identical characters in that row, column, or diagonal, and the game is over. We can return the corresponding character.
@@ -63,8 +63,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ i
-### **Python3**
-
```python
class Solution:
def tictactoe(self, board: List[str]) -> str:
@@ -95,8 +93,6 @@ class Solution:
return 'Pending' if has_empty_grid else 'Draw'
```
-### **Java**
-
```java
class Solution {
public String tictactoe(String[] board) {
@@ -132,8 +128,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -168,8 +162,6 @@ public:
};
```
-### **Go**
-
```go
func tictactoe(board []string) string {
n := len(board)
@@ -214,8 +206,6 @@ func abs(x int) int {
}
```
-### **TypeScript**
-
```ts
function tictactoe(board: string[]): string {
const n = board.length;
@@ -253,10 +243,6 @@ function tictactoe(board: string[]): string {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.05.Factorial Zeros/README.md b/lcci/16.05.Factorial Zeros/README.md
index b8f639ee621be..5329808dde1b7 100644
--- a/lcci/16.05.Factorial Zeros/README.md
+++ b/lcci/16.05.Factorial Zeros/README.md
@@ -19,9 +19,7 @@
## 解法
-
-
-**方法一:数学**
+### 方法一:数学
题目实际上是求 $[1,n]$ 中有多少个 $5$ 的因数。
@@ -36,10 +34,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def trailingZeroes(self, n: int) -> int:
@@ -50,10 +44,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
public int trailingZeroes(int n) {
@@ -67,8 +57,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -83,8 +71,6 @@ public:
};
```
-### **Go**
-
```go
func trailingZeroes(n int) int {
ans := 0
@@ -96,8 +82,6 @@ func trailingZeroes(n int) int {
}
```
-### **TypeScript**
-
```ts
function trailingZeroes(n: number): number {
let ans = 0;
@@ -109,10 +93,6 @@ function trailingZeroes(n: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.05.Factorial Zeros/README_EN.md b/lcci/16.05.Factorial Zeros/README_EN.md
index ed4a8574eede5..7c3f28b85fb94 100644
--- a/lcci/16.05.Factorial Zeros/README_EN.md
+++ b/lcci/16.05.Factorial Zeros/README_EN.md
@@ -27,7 +27,7 @@
## Solutions
-**Solution 1: Mathematics**
+### Solution 1: Mathematics
The problem is actually asking for the number of factors of $5$ in $[1,n]$.
@@ -42,8 +42,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$.
-### **Python3**
-
```python
class Solution:
def trailingZeroes(self, n: int) -> int:
@@ -54,8 +52,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
public int trailingZeroes(int n) {
@@ -69,8 +65,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -85,8 +79,6 @@ public:
};
```
-### **Go**
-
```go
func trailingZeroes(n int) int {
ans := 0
@@ -98,8 +90,6 @@ func trailingZeroes(n int) int {
}
```
-### **TypeScript**
-
```ts
function trailingZeroes(n: number): number {
let ans = 0;
@@ -111,10 +101,6 @@ function trailingZeroes(n: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.06.Smallest Difference/README.md b/lcci/16.06.Smallest Difference/README.md
index 9de7332c188aa..87e00393bdf6d 100644
--- a/lcci/16.06.Smallest Difference/README.md
+++ b/lcci/16.06.Smallest Difference/README.md
@@ -20,26 +20,14 @@
## 解法
-
-
-**方法一:排序 + 二分查找**
+### 方法一:排序 + 二分查找
我们可以对数组 $b$ 进行排序,并对数组 $a$ 中的每个元素 $x$ 在数组 $b$ 中进行二分查找,找到最接近 $x$ 的元素 $y$,那么 $x$ 和 $y$ 的差的绝对值就是 $x$ 和 $b$ 中最接近 $x$ 的元素的差的绝对值。
时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 $b$ 的长度。
-**方法二:排序 + 双指针**
-
-我们可以对数组 $a$ 和 $b$ 分别进行排序,然后使用双指针的方法,维护两个指针 $i$ 和 $j$,初始时分别指向数组 $a$ 和 $b$ 的起始位置。每一次,我们计算 $a[i]$ 和 $b[j]$ 的差的绝对值,并且更新答案。如果 $a[i]$ 和 $b[j]$ 指向的两个元素中的一个元素比另一个元素要小,则将指向较小元素的指针向前移动一步。当至少有一个指针超出数组范围时,遍历结束。
-
-时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 $a$ 和 $b$ 的长度。
-
-### **Python3**
-
-
-
```python
class Solution:
def smallestDifference(self, a: List[int], b: List[int]) -> int:
@@ -55,26 +43,6 @@ class Solution:
return ans
```
-```python
-class Solution:
- def smallestDifference(self, a: List[int], b: List[int]) -> int:
- a.sort()
- b.sort()
- i = j = 0
- ans = inf
- while i < len(a) and j < len(b):
- ans = min(ans, abs(a[i] - b[j]))
- if a[i] < b[j]:
- i += 1
- else:
- j += 1
- return ans
-```
-
-### **Java**
-
-
-
```java
class Solution {
public int smallestDifference(int[] a, int[] b) {
@@ -107,28 +75,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int smallestDifference(int[] a, int[] b) {
- Arrays.sort(a);
- Arrays.sort(b);
- int i = 0, j = 0;
- long ans = Long.MAX_VALUE;
- while (i < a.length && j < b.length) {
- ans = Math.min(ans, Math.abs((long) a[i] - (long) b[j]));
- if (a[i] < b[j]) {
- ++i;
- } else {
- ++j;
- }
- }
- return (int) ans;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -149,29 +95,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- int smallestDifference(vector& a, vector& b) {
- sort(a.begin(), a.end());
- sort(b.begin(), b.end());
- int i = 0, j = 0;
- long long ans = LONG_LONG_MAX;
- while (i < a.size() && j < b.size()) {
- ans = min(ans, abs(1LL * a[i] - 1LL * b[j]));
- if (a[i] < b[j]) {
- ++i;
- } else {
- ++j;
- }
- }
- return ans;
- }
-};
-```
-
-### **Go**
-
```go
func smallestDifference(a []int, b []int) int {
sort.Ints(b)
@@ -189,33 +112,6 @@ func smallestDifference(a []int, b []int) int {
}
```
-```go
-func smallestDifference(a []int, b []int) int {
- sort.Ints(a)
- sort.Ints(b)
- i, j := 0, 0
- var ans int = 1e18
- for i < len(a) && j < len(b) {
- ans = min(ans, abs(a[i]-b[j]))
- if a[i] < b[j] {
- i++
- } else {
- j++
- }
- }
- return ans
-}
-
-func abs(a int) int {
- if a < 0 {
- return -a
- }
- return a
-}
-```
-
-### **TypeScript**
-
```ts
function smallestDifference(a: number[], b: number[]): number {
b.sort((a, b) => a - b);
@@ -245,6 +141,98 @@ function smallestDifference(a: number[], b: number[]): number {
}
```
+
+
+### 方法二:排序 + 双指针
+
+我们可以对数组 $a$ 和 $b$ 分别进行排序,然后使用双指针的方法,维护两个指针 $i$ 和 $j$,初始时分别指向数组 $a$ 和 $b$ 的起始位置。每一次,我们计算 $a[i]$ 和 $b[j]$ 的差的绝对值,并且更新答案。如果 $a[i]$ 和 $b[j]$ 指向的两个元素中的一个元素比另一个元素要小,则将指向较小元素的指针向前移动一步。当至少有一个指针超出数组范围时,遍历结束。
+
+时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 $a$ 和 $b$ 的长度。
+
+
+
+```python
+class Solution:
+ def smallestDifference(self, a: List[int], b: List[int]) -> int:
+ a.sort()
+ b.sort()
+ i = j = 0
+ ans = inf
+ while i < len(a) and j < len(b):
+ ans = min(ans, abs(a[i] - b[j]))
+ if a[i] < b[j]:
+ i += 1
+ else:
+ j += 1
+ return ans
+```
+
+```java
+class Solution {
+ public int smallestDifference(int[] a, int[] b) {
+ Arrays.sort(a);
+ Arrays.sort(b);
+ int i = 0, j = 0;
+ long ans = Long.MAX_VALUE;
+ while (i < a.length && j < b.length) {
+ ans = Math.min(ans, Math.abs((long) a[i] - (long) b[j]));
+ if (a[i] < b[j]) {
+ ++i;
+ } else {
+ ++j;
+ }
+ }
+ return (int) ans;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ int smallestDifference(vector& a, vector& b) {
+ sort(a.begin(), a.end());
+ sort(b.begin(), b.end());
+ int i = 0, j = 0;
+ long long ans = LONG_LONG_MAX;
+ while (i < a.size() && j < b.size()) {
+ ans = min(ans, abs(1LL * a[i] - 1LL * b[j]));
+ if (a[i] < b[j]) {
+ ++i;
+ } else {
+ ++j;
+ }
+ }
+ return ans;
+ }
+};
+```
+
+```go
+func smallestDifference(a []int, b []int) int {
+ sort.Ints(a)
+ sort.Ints(b)
+ i, j := 0, 0
+ var ans int = 1e18
+ for i < len(a) && j < len(b) {
+ ans = min(ans, abs(a[i]-b[j]))
+ if a[i] < b[j] {
+ i++
+ } else {
+ j++
+ }
+ }
+ return ans
+}
+
+func abs(a int) int {
+ if a < 0 {
+ return -a
+ }
+ return a
+}
+```
+
```ts
function smallestDifference(a: number[], b: number[]): number {
a.sort((a, b) => a - b);
@@ -263,10 +251,6 @@ function smallestDifference(a: number[], b: number[]): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.06.Smallest Difference/README_EN.md b/lcci/16.06.Smallest Difference/README_EN.md
index 3f86e0166eca5..683a3a99131a4 100644
--- a/lcci/16.06.Smallest Difference/README_EN.md
+++ b/lcci/16.06.Smallest Difference/README_EN.md
@@ -26,26 +26,17 @@
## Solutions
-**Solution 1: Sorting + Binary Search**
+### Solution 1: Sorting + Binary Search
We can sort the array $b$, and for each element $x$ in array $a$, perform a binary search in array $b$ to find the element $y$ closest to $x$. Then, the absolute difference between $x$ and $y$ is the absolute difference between $x$ and the closest element in $b$.
The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of array $b$.
-**Solution 2: Sorting + Two Pointers**
-
-We can sort both arrays $a$ and $b$, and use two pointers $i$ and $j$ to maintain the current positions in the two arrays. Initially, $i$ and $j$ point to the beginning of arrays $a$ and $b$, respectively. At each step, we calculate the absolute difference between $a[i]$ and $b[j]$, and update the answer. If one of the elements pointed to by $i$ and $j$ is smaller than the other, we move the pointer pointing to the smaller element forward by one step. The traversal ends when at least one of the pointers goes beyond the array range.
-
-The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of arrays $a$ and $b$.
-
-### **Python3**
-
```python
class Solution:
def smallestDifference(self, a: List[int], b: List[int]) -> int:
- a.sort()
b.sort()
ans = inf
n = len(b)
@@ -58,23 +49,6 @@ class Solution:
return ans
```
-```python
-class Solution:
- def smallestDifference(self, a: List[int], b: List[int]) -> int:
- b.sort()
- ans = inf
- n = len(b)
- for x in a:
- j = bisect_left(b, x)
- if j < n:
- ans = min(ans, b[j] - x)
- if j:
- ans = min(ans, x - b[j - 1])
- return ans
-```
-
-### **Java**
-
```java
class Solution {
public int smallestDifference(int[] a, int[] b) {
@@ -107,28 +81,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int smallestDifference(int[] a, int[] b) {
- Arrays.sort(a);
- Arrays.sort(b);
- int i = 0, j = 0;
- long ans = Long.MAX_VALUE;
- while (i < a.length && j < b.length) {
- ans = Math.min(ans, Math.abs((long) a[i] - (long) b[j]));
- if (a[i] < b[j]) {
- ++i;
- } else {
- ++j;
- }
- }
- return (int) ans;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -149,29 +101,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- int smallestDifference(vector& a, vector& b) {
- sort(a.begin(), a.end());
- sort(b.begin(), b.end());
- int i = 0, j = 0;
- long long ans = LONG_LONG_MAX;
- while (i < a.size() && j < b.size()) {
- ans = min(ans, abs(1LL * a[i] - 1LL * b[j]));
- if (a[i] < b[j]) {
- ++i;
- } else {
- ++j;
- }
- }
- return ans;
- }
-};
-```
-
-### **Go**
-
```go
func smallestDifference(a []int, b []int) int {
sort.Ints(b)
@@ -189,33 +118,6 @@ func smallestDifference(a []int, b []int) int {
}
```
-```go
-func smallestDifference(a []int, b []int) int {
- sort.Ints(a)
- sort.Ints(b)
- i, j := 0, 0
- var ans int = 1e18
- for i < len(a) && j < len(b) {
- ans = min(ans, abs(a[i]-b[j]))
- if a[i] < b[j] {
- i++
- } else {
- j++
- }
- }
- return ans
-}
-
-func abs(a int) int {
- if a < 0 {
- return -a
- }
- return a
-}
-```
-
-### **TypeScript**
-
```ts
function smallestDifference(a: number[], b: number[]): number {
b.sort((a, b) => a - b);
@@ -245,6 +147,98 @@ function smallestDifference(a: number[], b: number[]): number {
}
```
+
+
+### Solution 2: Sorting + Two Pointers
+
+We can sort both arrays $a$ and $b$, and use two pointers $i$ and $j$ to maintain the current positions in the two arrays. Initially, $i$ and $j$ point to the beginning of arrays $a$ and $b$, respectively. At each step, we calculate the absolute difference between $a[i]$ and $b[j]$, and update the answer. If one of the elements pointed to by $i$ and $j$ is smaller than the other, we move the pointer pointing to the smaller element forward by one step. The traversal ends when at least one of the pointers goes beyond the array range.
+
+The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of arrays $a$ and $b$.
+
+
+
+```python
+class Solution:
+ def smallestDifference(self, a: List[int], b: List[int]) -> int:
+ a.sort()
+ b.sort()
+ i = j = 0
+ ans = inf
+ while i < len(a) and j < len(b):
+ ans = min(ans, abs(a[i] - b[j]))
+ if a[i] < b[j]:
+ i += 1
+ else:
+ j += 1
+ return ans
+```
+
+```java
+class Solution {
+ public int smallestDifference(int[] a, int[] b) {
+ Arrays.sort(a);
+ Arrays.sort(b);
+ int i = 0, j = 0;
+ long ans = Long.MAX_VALUE;
+ while (i < a.length && j < b.length) {
+ ans = Math.min(ans, Math.abs((long) a[i] - (long) b[j]));
+ if (a[i] < b[j]) {
+ ++i;
+ } else {
+ ++j;
+ }
+ }
+ return (int) ans;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ int smallestDifference(vector& a, vector& b) {
+ sort(a.begin(), a.end());
+ sort(b.begin(), b.end());
+ int i = 0, j = 0;
+ long long ans = LONG_LONG_MAX;
+ while (i < a.size() && j < b.size()) {
+ ans = min(ans, abs(1LL * a[i] - 1LL * b[j]));
+ if (a[i] < b[j]) {
+ ++i;
+ } else {
+ ++j;
+ }
+ }
+ return ans;
+ }
+};
+```
+
+```go
+func smallestDifference(a []int, b []int) int {
+ sort.Ints(a)
+ sort.Ints(b)
+ i, j := 0, 0
+ var ans int = 1e18
+ for i < len(a) && j < len(b) {
+ ans = min(ans, abs(a[i]-b[j]))
+ if a[i] < b[j] {
+ i++
+ } else {
+ j++
+ }
+ }
+ return ans
+}
+
+func abs(a int) int {
+ if a < 0 {
+ return -a
+ }
+ return a
+}
+```
+
```ts
function smallestDifference(a: number[], b: number[]): number {
a.sort((a, b) => a - b);
@@ -263,10 +257,6 @@ function smallestDifference(a: number[], b: number[]): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.07.Maximum/README.md b/lcci/16.07.Maximum/README.md
index 62be319c07af0..ab1ec488e7dbd 100644
--- a/lcci/16.07.Maximum/README.md
+++ b/lcci/16.07.Maximum/README.md
@@ -14,9 +14,7 @@
## 解法
-
-
-**方法一:位运算**
+### 方法一:位运算
我们可以提取 $a-b$ 的符号位 $k$,如果符号位为 $1$,说明 $a \lt b$;如果符号位为 $0$,说明 $a \ge b$。
@@ -26,10 +24,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def maximum(self, a: int, b: int) -> int:
@@ -37,10 +31,6 @@ class Solution:
return a * (k ^ 1) + b * k
```
-### **Java**
-
-
-
```java
class Solution {
public int maximum(int a, int b) {
@@ -50,8 +40,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -62,8 +50,6 @@ public:
};
```
-### **Go**
-
```go
func maximum(a int, b int) int {
k := (a - b) >> 63 & 1
@@ -71,8 +57,6 @@ func maximum(a int, b int) int {
}
```
-### **TypeScript**
-
```ts
function maximum(a: number, b: number): number {
const k: number = Number(((BigInt(a) - BigInt(b)) >> BigInt(63)) & BigInt(1));
@@ -80,10 +64,6 @@ function maximum(a: number, b: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.07.Maximum/README_EN.md b/lcci/16.07.Maximum/README_EN.md
index b27f482393d03..b5c96bf559f0d 100644
--- a/lcci/16.07.Maximum/README_EN.md
+++ b/lcci/16.07.Maximum/README_EN.md
@@ -16,7 +16,7 @@
## Solutions
-**Solution 1: Bitwise Operation**
+### Solution 1: Bitwise Operation
We can extract the sign bit $k$ of $a-b$. If the sign bit is $1$, it means $a \lt b$; if the sign bit is $0$, it means $a \ge b$.
@@ -26,8 +26,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$.
-### **Python3**
-
```python
class Solution:
def maximum(self, a: int, b: int) -> int:
@@ -35,8 +33,6 @@ class Solution:
return a * (k ^ 1) + b * k
```
-### **Java**
-
```java
class Solution {
public int maximum(int a, int b) {
@@ -46,8 +42,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -58,8 +52,6 @@ public:
};
```
-### **Go**
-
```go
func maximum(a int, b int) int {
k := (a - b) >> 63 & 1
@@ -67,8 +59,6 @@ func maximum(a int, b int) int {
}
```
-### **TypeScript**
-
```ts
function maximum(a: number, b: number): number {
const k: number = Number(((BigInt(a) - BigInt(b)) >> BigInt(63)) & BigInt(1));
@@ -76,10 +66,6 @@ function maximum(a: number, b: number): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.08.English Int/README.md b/lcci/16.08.English Int/README.md
index 5fe9bfcb6b0d1..5dabf532fca92 100644
--- a/lcci/16.08.English Int/README.md
+++ b/lcci/16.08.English Int/README.md
@@ -22,29 +22,4 @@
## 解法
-
-
-
-### **Python3**
-
-
-
-```python
-
-```
-
-### **Java**
-
-
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/16.08.English Int/README_EN.md b/lcci/16.08.English Int/README_EN.md
index af0d5379ce48c..fabf013c19aa6 100644
--- a/lcci/16.08.English Int/README_EN.md
+++ b/lcci/16.08.English Int/README_EN.md
@@ -36,24 +36,4 @@
## Solutions
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/16.09.Operations/README.md b/lcci/16.09.Operations/README.md
index f1881316ef35c..311ade1b00727 100644
--- a/lcci/16.09.Operations/README.md
+++ b/lcci/16.09.Operations/README.md
@@ -27,29 +27,4 @@ operations.divide(5, -2); //返回-2
## 解法
-
-
-
-### **Python3**
-
-
-
-```python
-
-```
-
-### **Java**
-
-
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/16.09.Operations/README_EN.md b/lcci/16.09.Operations/README_EN.md
index 7cf9237752394..c7cdc4937691d 100644
--- a/lcci/16.09.Operations/README_EN.md
+++ b/lcci/16.09.Operations/README_EN.md
@@ -32,24 +32,4 @@ operations.divide(5, -2); //returns -2
## Solutions
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
+
diff --git a/lcci/16.10.Living People/README.md b/lcci/16.10.Living People/README.md
index caab2ba2c13c6..5f1f54f3efeed 100644
--- a/lcci/16.10.Living People/README.md
+++ b/lcci/16.10.Living People/README.md
@@ -23,9 +23,7 @@ death = {1948, 1951, 2000}
## 解法
-
-
-**方法一:差分数组**
+### 方法一:差分数组
题目实际上是对一个连续的区间进行加减操作,然后求最大值。这种情况下可以使用差分数组来解决。
@@ -37,10 +35,6 @@ death = {1948, 1951, 2000}
-### **Python3**
-
-
-
```python
class Solution:
def maxAliveYear(self, birth: List[int], death: List[int]) -> int:
@@ -59,10 +53,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
public int maxAliveYear(int[] birth, int[] death) {
@@ -88,8 +78,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -116,8 +104,6 @@ public:
};
```
-### **Go**
-
```go
func maxAliveYear(birth []int, death []int) (ans int) {
base := 1900
@@ -140,8 +126,6 @@ func maxAliveYear(birth []int, death []int) (ans int) {
}
```
-### **TypeScript**
-
```ts
function maxAliveYear(birth: number[], death: number[]): number {
const base = 1900;
@@ -164,8 +148,6 @@ function maxAliveYear(birth: number[], death: number[]): number {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn max_alive_year(birth: Vec, death: Vec) -> i32 {
@@ -191,10 +173,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.10.Living People/README_EN.md b/lcci/16.10.Living People/README_EN.md
index 83c6e001e16f1..f94d95e3d56e4 100644
--- a/lcci/16.10.Living People/README_EN.md
+++ b/lcci/16.10.Living People/README_EN.md
@@ -31,7 +31,7 @@ death = {1948, 1951, 2000}
## Solutions
-**Solution 1: Difference Array**
+### Solution 1: Difference Array
The problem is actually about performing addition and subtraction operations on a continuous interval, and then finding the maximum value. This can be solved using a difference array.
@@ -43,8 +43,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is
-### **Python3**
-
```python
class Solution:
def maxAliveYear(self, birth: List[int], death: List[int]) -> int:
@@ -63,8 +61,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
public int maxAliveYear(int[] birth, int[] death) {
@@ -90,8 +86,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -118,8 +112,6 @@ public:
};
```
-### **Go**
-
```go
func maxAliveYear(birth []int, death []int) (ans int) {
base := 1900
@@ -142,8 +134,6 @@ func maxAliveYear(birth []int, death []int) (ans int) {
}
```
-### **TypeScript**
-
```ts
function maxAliveYear(birth: number[], death: number[]): number {
const base = 1900;
@@ -166,8 +156,6 @@ function maxAliveYear(birth: number[], death: number[]): number {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn max_alive_year(birth: Vec, death: Vec) -> i32 {
@@ -193,10 +181,6 @@ impl Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.11.Diving Board/README.md b/lcci/16.11.Diving Board/README.md
index d3622ee13692b..b98e0fcc26c80 100644
--- a/lcci/16.11.Diving Board/README.md
+++ b/lcci/16.11.Diving Board/README.md
@@ -23,9 +23,7 @@ k = 3
## 解法
-
-
-**方法一:分类讨论**
+### 方法一:分类讨论
如果 $k=0$,则不存在任何一种方案,我们可以直接返回空列表。
@@ -37,10 +35,6 @@ k = 3
-### **Python3**
-
-
-
```python
class Solution:
def divingBoard(self, shorter: int, longer: int, k: int) -> List[int]:
@@ -54,10 +48,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
public int[] divingBoard(int shorter, int longer, int k) {
@@ -76,8 +66,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -92,8 +80,6 @@ public:
};
```
-### **Go**
-
```go
func divingBoard(shorter int, longer int, k int) []int {
if k == 0 {
@@ -110,8 +96,6 @@ func divingBoard(shorter int, longer int, k int) []int {
}
```
-### **TypeScript**
-
```ts
function divingBoard(shorter: number, longer: number, k: number): number[] {
if (k === 0) {
@@ -128,10 +112,6 @@ function divingBoard(shorter: number, longer: number, k: number): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.11.Diving Board/README_EN.md b/lcci/16.11.Diving Board/README_EN.md
index 697fc62500b68..bf94360b809af 100644
--- a/lcci/16.11.Diving Board/README_EN.md
+++ b/lcci/16.11.Diving Board/README_EN.md
@@ -33,7 +33,7 @@ k = 3
## Solutions
-**Solution 1: Case Analysis**
+### Solution 1: Case Analysis
If $k=0$, there is no solution, and we can directly return an empty list.
@@ -45,8 +45,6 @@ The time complexity is $O(k)$, where $k$ is the number of boards. Ignoring the s
-### **Python3**
-
```python
class Solution:
def divingBoard(self, shorter: int, longer: int, k: int) -> List[int]:
@@ -60,8 +58,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
public int[] divingBoard(int shorter, int longer, int k) {
@@ -80,8 +76,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -96,8 +90,6 @@ public:
};
```
-### **Go**
-
```go
func divingBoard(shorter int, longer int, k int) []int {
if k == 0 {
@@ -114,8 +106,6 @@ func divingBoard(shorter int, longer int, k int) []int {
}
```
-### **TypeScript**
-
```ts
function divingBoard(shorter: number, longer: number, k: number): number[] {
if (k === 0) {
@@ -132,10 +122,6 @@ function divingBoard(shorter: number, longer: number, k: number): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.13.Bisect Squares/README.md b/lcci/16.13.Bisect Squares/README.md
index e12251f879bd2..9456a498b3ae4 100644
--- a/lcci/16.13.Bisect Squares/README.md
+++ b/lcci/16.13.Bisect Squares/README.md
@@ -24,9 +24,7 @@ square2 = {0, -1, 2}
## 解法
-
-
-**方法一:几何数学**
+### 方法一:几何数学
我们知道,如果一条直线可以将两个正方形平分,那么这条直线一定会经过两个正方形的中心点。因此,我们可以先求出两个正方形的中心点,分别记为 $(x_1, y_1)$ 和 $(x_2, y_2)$。
@@ -41,10 +39,6 @@ square2 = {0, -1, 2}
-### **Python3**
-
-
-
```python
class Solution:
def cutSquares(self, square1: List[int], square2: List[int]) -> List[float]:
@@ -71,10 +65,6 @@ class Solution:
return [x3, y3, x4, y4]
```
-### **Java**
-
-
-
```java
class Solution {
public double[] cutSquares(int[] square1, int[] square2) {
@@ -109,8 +99,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -146,8 +134,6 @@ public:
};
```
-### **Go**
-
```go
func cutSquares(square1 []int, square2 []int) []float64 {
x1, y1 := float64(square1[0])+float64(square1[2])/2, float64(square1[1])+float64(square1[2])/2
@@ -178,8 +164,6 @@ func cutSquares(square1 []int, square2 []int) []float64 {
}
```
-### **TypeScript**
-
```ts
function cutSquares(square1: number[], square2: number[]): number[] {
const x1 = square1[0] + square1[2] / 2;
@@ -212,10 +196,6 @@ function cutSquares(square1: number[], square2: number[]): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.13.Bisect Squares/README_EN.md b/lcci/16.13.Bisect Squares/README_EN.md
index 5f6ea8497f77c..0730df152e987 100644
--- a/lcci/16.13.Bisect Squares/README_EN.md
+++ b/lcci/16.13.Bisect Squares/README_EN.md
@@ -29,7 +29,7 @@ square2 = {0, -1, 2}
## Solutions
-**Solution 1: Geometric Mathematics**
+### Solution 1: Geometric Mathematics
We know that if a line can bisect two squares, then the line must pass through the centers of the two squares. Therefore, we can first calculate the centers of the two squares, denoted as $(x_1, y_1)$ and $(x_2, y_2)$, respectively.
@@ -44,8 +44,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$.
-### **Python3**
-
```python
class Solution:
def cutSquares(self, square1: List[int], square2: List[int]) -> List[float]:
@@ -72,8 +70,6 @@ class Solution:
return [x3, y3, x4, y4]
```
-### **Java**
-
```java
class Solution {
public double[] cutSquares(int[] square1, int[] square2) {
@@ -108,8 +104,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -145,8 +139,6 @@ public:
};
```
-### **Go**
-
```go
func cutSquares(square1 []int, square2 []int) []float64 {
x1, y1 := float64(square1[0])+float64(square1[2])/2, float64(square1[1])+float64(square1[2])/2
@@ -177,8 +169,6 @@ func cutSquares(square1 []int, square2 []int) []float64 {
}
```
-### **TypeScript**
-
```ts
function cutSquares(square1: number[], square2: number[]): number[] {
const x1 = square1[0] + square1[2] / 2;
@@ -211,10 +201,6 @@ function cutSquares(square1: number[], square2: number[]): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.14.Best Line/README.md b/lcci/16.14.Best Line/README.md
index ef6e4b17beb21..92ba1a29236b4 100644
--- a/lcci/16.14.Best Line/README.md
+++ b/lcci/16.14.Best Line/README.md
@@ -20,30 +20,14 @@
## 解法
-
-
-**方法一:暴力枚举**
+### 方法一:暴力枚举
我们可以枚举任意两个点 $(x_1, y_1), (x_2, y_2)$,把这两个点连成一条直线,那么此时这条直线上的点的个数就是 2,接下来我们再枚举其他点 $(x_3, y_3)$,判断它们是否在同一条直线上,如果在,那么直线上的点的个数就加 1,如果不在,那么直线上的点的个数不变。找出所有直线上的点的个数的最大值,其对应的最小的两个点的编号即为答案。
时间复杂度 $O(n^3)$,空间复杂度 $O(1)$。其中 $n$ 是数组 `points` 的长度。
-**方法二:枚举 + 哈希表**
-
-我们可以枚举一个点 $(x_1, y_1)$,把其他所有点 $(x_2, y_2)$ 与 $(x_1, y_1)$ 连成的直线的斜率存入哈希表中,斜率相同的点在同一条直线上,哈希表的键为斜率,值为直线上的点的个数。找出哈希表中的最大值,即为答案。为了避免精度问题,我们可以将斜率 $\frac{y_2 - y_1}{x_2 - x_1}$ 进行约分,约分的方法是求最大公约数,然后分子分母同时除以最大公约数,将求得的分子分母作为哈希表的键。
-
-时间复杂度 $O(n^2 \times \log m)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别是数组 `points` 的长度和数组 `points` 所有横纵坐标差的最大值。
-
-相似题目:
-
-- [149. 直线上最多的点数](/solution/0100-0199/0149.Max%20Points%20on%20a%20Line/README.md)
-
-### **Python3**
-
-
-
```python
class Solution:
def bestLine(self, points: List[List[int]]) -> List[int]:
@@ -65,33 +49,6 @@ class Solution:
return [x, y]
```
-```python
-class Solution:
- def bestLine(self, points: List[List[int]]) -> List[int]:
- def gcd(a, b):
- return a if b == 0 else gcd(b, a % b)
-
- n = len(points)
- mx = 0
- for i in range(n):
- x1, y1 = points[i]
- cnt = defaultdict(list)
- for j in range(i + 1, n):
- x2, y2 = points[j]
- dx, dy = x2 - x1, y2 - y1
- g = gcd(dx, dy)
- k = (dx // g, dy // g)
- cnt[k].append((i, j))
- if mx < len(cnt[k]) or (mx == len(cnt[k]) and (x, y) > cnt[k][0]):
- mx = len(cnt[k])
- x, y = cnt[k][0]
- return [x, y]
-```
-
-### **Java**
-
-
-
```java
class Solution {
public int[] bestLine(int[][] points) {
@@ -123,6 +80,101 @@ class Solution {
}
```
+```cpp
+class Solution {
+public:
+ vector bestLine(vector>& points) {
+ int n = points.size();
+ int mx = 0;
+ vector ans(2);
+ for (int i = 0; i < n; ++i) {
+ int x1 = points[i][0], y1 = points[i][1];
+ for (int j = i + 1; j < n; ++j) {
+ int x2 = points[j][0], y2 = points[j][1];
+ int cnt = 2;
+ for (int k = j + 1; k < n; ++k) {
+ int x3 = points[k][0], y3 = points[k][1];
+ long a = (long) (y2 - y1) * (x3 - x1);
+ long b = (long) (y3 - y1) * (x2 - x1);
+ cnt += a == b;
+ }
+ if (mx < cnt) {
+ mx = cnt;
+ ans[0] = i;
+ ans[1] = j;
+ }
+ }
+ }
+ return ans;
+ }
+};
+```
+
+```go
+func bestLine(points [][]int) []int {
+ n := len(points)
+ ans := make([]int, 2)
+ mx := 0
+ for i := 0; i < n; i++ {
+ x1, y1 := points[i][0], points[i][1]
+ for j := i + 1; j < n; j++ {
+ x2, y2 := points[j][0], points[j][1]
+ cnt := 2
+ for k := j + 1; k < n; k++ {
+ x3, y3 := points[k][0], points[k][1]
+ a := (y2 - y1) * (x3 - x1)
+ b := (y3 - y1) * (x2 - x1)
+ if a == b {
+ cnt++
+ }
+ }
+ if mx < cnt {
+ mx = cnt
+ ans[0], ans[1] = i, j
+ }
+ }
+ }
+ return ans
+}
+```
+
+
+
+### 方法二:枚举 + 哈希表
+
+我们可以枚举一个点 $(x_1, y_1)$,把其他所有点 $(x_2, y_2)$ 与 $(x_1, y_1)$ 连成的直线的斜率存入哈希表中,斜率相同的点在同一条直线上,哈希表的键为斜率,值为直线上的点的个数。找出哈希表中的最大值,即为答案。为了避免精度问题,我们可以将斜率 $\frac{y_2 - y_1}{x_2 - x_1}$ 进行约分,约分的方法是求最大公约数,然后分子分母同时除以最大公约数,将求得的分子分母作为哈希表的键。
+
+时间复杂度 $O(n^2 \times \log m)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别是数组 `points` 的长度和数组 `points` 所有横纵坐标差的最大值。
+
+相似题目:
+
+- [149. 直线上最多的点数](/solution/0100-0199/0149.Max%20Points%20on%20a%20Line/README.md)
+
+
+
+```python
+class Solution:
+ def bestLine(self, points: List[List[int]]) -> List[int]:
+ def gcd(a, b):
+ return a if b == 0 else gcd(b, a % b)
+
+ n = len(points)
+ mx = 0
+ for i in range(n):
+ x1, y1 = points[i]
+ cnt = defaultdict(list)
+ for j in range(i + 1, n):
+ x2, y2 = points[j]
+ dx, dy = x2 - x1, y2 - y1
+ g = gcd(dx, dy)
+ k = (dx // g, dy // g)
+ cnt[k].append((i, j))
+ if mx < len(cnt[k]) or (mx == len(cnt[k]) and (x, y) > cnt[k][0]):
+ mx = len(cnt[k])
+ x, y = cnt[k][0]
+ return [x, y]
+```
+
```java
class Solution {
public int[] bestLine(int[][] points) {
@@ -157,38 +209,6 @@ class Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- vector bestLine(vector>& points) {
- int n = points.size();
- int mx = 0;
- vector ans(2);
- for (int i = 0; i < n; ++i) {
- int x1 = points[i][0], y1 = points[i][1];
- for (int j = i + 1; j < n; ++j) {
- int x2 = points[j][0], y2 = points[j][1];
- int cnt = 2;
- for (int k = j + 1; k < n; ++k) {
- int x3 = points[k][0], y3 = points[k][1];
- long a = (long) (y2 - y1) * (x3 - x1);
- long b = (long) (y3 - y1) * (x2 - x1);
- cnt += a == b;
- }
- if (mx < cnt) {
- mx = cnt;
- ans[0] = i;
- ans[1] = j;
- }
- }
- }
- return ans;
- }
-};
-```
-
```cpp
class Solution {
public:
@@ -220,36 +240,6 @@ public:
};
```
-### **Go**
-
-```go
-func bestLine(points [][]int) []int {
- n := len(points)
- ans := make([]int, 2)
- mx := 0
- for i := 0; i < n; i++ {
- x1, y1 := points[i][0], points[i][1]
- for j := i + 1; j < n; j++ {
- x2, y2 := points[j][0], points[j][1]
- cnt := 2
- for k := j + 1; k < n; k++ {
- x3, y3 := points[k][0], points[k][1]
- a := (y2 - y1) * (x3 - x1)
- b := (y3 - y1) * (x2 - x1)
- if a == b {
- cnt++
- }
- }
- if mx < cnt {
- mx = cnt
- ans[0], ans[1] = i, j
- }
- }
- }
- return ans
-}
-```
-
```go
func bestLine(points [][]int) []int {
n := len(points)
@@ -282,10 +272,6 @@ func gcd(a, b int) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.14.Best Line/README_EN.md b/lcci/16.14.Best Line/README_EN.md
index 43304d063f38e..95e921f450a1a 100644
--- a/lcci/16.14.Best Line/README_EN.md
+++ b/lcci/16.14.Best Line/README_EN.md
@@ -24,22 +24,14 @@
## Solutions
-**Solution 1: Brute Force**
+### Solution 1: Brute Force
We can enumerate any two points $(x_1, y_1), (x_2, y_2)$, connect these two points into a line, and the number of points on this line is 2. Then we enumerate other points $(x_3, y_3)$, and determine whether they are on the same line. If they are, the number of points on the line increases by 1; otherwise, the number of points on the line remains the same. Find the maximum number of points on a line, and the corresponding smallest two point indices are the answer.
The time complexity is $O(n^3)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array `points`.
-**Solution 2: Enumeration + Hash Table**
-
-We can enumerate a point $(x_1, y_1)$, store the slope of the line connecting $(x_1, y_1)$ and all other points $(x_2, y_2)$ in a hash table. Points with the same slope are on the same line, and the key of the hash table is the slope, and the value is the number of points on the line. Find the maximum value in the hash table, which is the answer. To avoid precision issues, we can reduce the slope $\frac{y_2 - y_1}{x_2 - x_1}$, and the reduction method is to find the greatest common divisor, and then divide the numerator and denominator by the greatest common divisor. The resulting numerator and denominator are used as the key of the hash table.
-
-The time complexity is $O(n^2 \times \log m)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the length of the array `points` and the maximum difference between all horizontal and vertical coordinates in the array `points`, respectively.
-
-### **Python3**
-
```python
class Solution:
def bestLine(self, points: List[List[int]]) -> List[int]:
@@ -61,31 +53,6 @@ class Solution:
return [x, y]
```
-```python
-class Solution:
- def bestLine(self, points: List[List[int]]) -> List[int]:
- def gcd(a, b):
- return a if b == 0 else gcd(b, a % b)
-
- n = len(points)
- mx = 0
- for i in range(n):
- x1, y1 = points[i]
- cnt = defaultdict(list)
- for j in range(i + 1, n):
- x2, y2 = points[j]
- dx, dy = x2 - x1, y2 - y1
- g = gcd(dx, dy)
- k = (dx // g, dy // g)
- cnt[k].append((i, j))
- if mx < len(cnt[k]) or (mx == len(cnt[k]) and (x, y) > cnt[k][0]):
- mx = len(cnt[k])
- x, y = cnt[k][0]
- return [x, y]
-```
-
-### **Java**
-
```java
class Solution {
public int[] bestLine(int[][] points) {
@@ -117,6 +84,97 @@ class Solution {
}
```
+```cpp
+class Solution {
+public:
+ vector bestLine(vector>& points) {
+ int n = points.size();
+ int mx = 0;
+ vector ans(2);
+ for (int i = 0; i < n; ++i) {
+ int x1 = points[i][0], y1 = points[i][1];
+ for (int j = i + 1; j < n; ++j) {
+ int x2 = points[j][0], y2 = points[j][1];
+ int cnt = 2;
+ for (int k = j + 1; k < n; ++k) {
+ int x3 = points[k][0], y3 = points[k][1];
+ long a = (long) (y2 - y1) * (x3 - x1);
+ long b = (long) (y3 - y1) * (x2 - x1);
+ cnt += a == b;
+ }
+ if (mx < cnt) {
+ mx = cnt;
+ ans[0] = i;
+ ans[1] = j;
+ }
+ }
+ }
+ return ans;
+ }
+};
+```
+
+```go
+func bestLine(points [][]int) []int {
+ n := len(points)
+ ans := make([]int, 2)
+ mx := 0
+ for i := 0; i < n; i++ {
+ x1, y1 := points[i][0], points[i][1]
+ for j := i + 1; j < n; j++ {
+ x2, y2 := points[j][0], points[j][1]
+ cnt := 2
+ for k := j + 1; k < n; k++ {
+ x3, y3 := points[k][0], points[k][1]
+ a := (y2 - y1) * (x3 - x1)
+ b := (y3 - y1) * (x2 - x1)
+ if a == b {
+ cnt++
+ }
+ }
+ if mx < cnt {
+ mx = cnt
+ ans[0], ans[1] = i, j
+ }
+ }
+ }
+ return ans
+}
+```
+
+
+
+### Solution 2: Enumeration + Hash Table
+
+We can enumerate a point $(x_1, y_1)$, store the slope of the line connecting $(x_1, y_1)$ and all other points $(x_2, y_2)$ in a hash table. Points with the same slope are on the same line, and the key of the hash table is the slope, and the value is the number of points on the line. Find the maximum value in the hash table, which is the answer. To avoid precision issues, we can reduce the slope $\frac{y_2 - y_1}{x_2 - x_1}$, and the reduction method is to find the greatest common divisor, and then divide the numerator and denominator by the greatest common divisor. The resulting numerator and denominator are used as the key of the hash table.
+
+The time complexity is $O(n^2 \times \log m)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the length of the array `points` and the maximum difference between all horizontal and vertical coordinates in the array `points`, respectively.
+
+
+
+```python
+class Solution:
+ def bestLine(self, points: List[List[int]]) -> List[int]:
+ def gcd(a, b):
+ return a if b == 0 else gcd(b, a % b)
+
+ n = len(points)
+ mx = 0
+ for i in range(n):
+ x1, y1 = points[i]
+ cnt = defaultdict(list)
+ for j in range(i + 1, n):
+ x2, y2 = points[j]
+ dx, dy = x2 - x1, y2 - y1
+ g = gcd(dx, dy)
+ k = (dx // g, dy // g)
+ cnt[k].append((i, j))
+ if mx < len(cnt[k]) or (mx == len(cnt[k]) and (x, y) > cnt[k][0]):
+ mx = len(cnt[k])
+ x, y = cnt[k][0]
+ return [x, y]
+```
+
```java
class Solution {
public int[] bestLine(int[][] points) {
@@ -151,38 +209,6 @@ class Solution {
}
```
-### **C++**
-
-```cpp
-class Solution {
-public:
- vector bestLine(vector>& points) {
- int n = points.size();
- int mx = 0;
- vector ans(2);
- for (int i = 0; i < n; ++i) {
- int x1 = points[i][0], y1 = points[i][1];
- for (int j = i + 1; j < n; ++j) {
- int x2 = points[j][0], y2 = points[j][1];
- int cnt = 2;
- for (int k = j + 1; k < n; ++k) {
- int x3 = points[k][0], y3 = points[k][1];
- long a = (long) (y2 - y1) * (x3 - x1);
- long b = (long) (y3 - y1) * (x2 - x1);
- cnt += a == b;
- }
- if (mx < cnt) {
- mx = cnt;
- ans[0] = i;
- ans[1] = j;
- }
- }
- }
- return ans;
- }
-};
-```
-
```cpp
class Solution {
public:
@@ -214,36 +240,6 @@ public:
};
```
-### **Go**
-
-```go
-func bestLine(points [][]int) []int {
- n := len(points)
- ans := make([]int, 2)
- mx := 0
- for i := 0; i < n; i++ {
- x1, y1 := points[i][0], points[i][1]
- for j := i + 1; j < n; j++ {
- x2, y2 := points[j][0], points[j][1]
- cnt := 2
- for k := j + 1; k < n; k++ {
- x3, y3 := points[k][0], points[k][1]
- a := (y2 - y1) * (x3 - x1)
- b := (y3 - y1) * (x2 - x1)
- if a == b {
- cnt++
- }
- }
- if mx < cnt {
- mx = cnt
- ans[0], ans[1] = i, j
- }
- }
- }
- return ans
-}
-```
-
```go
func bestLine(points [][]int) []int {
n := len(points)
@@ -276,10 +272,6 @@ func gcd(a, b int) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.15.Master Mind/README.md b/lcci/16.15.Master Mind/README.md
index 47e35a45bd18a..0f4bed11acc0d 100644
--- a/lcci/16.15.Master Mind/README.md
+++ b/lcci/16.15.Master Mind/README.md
@@ -21,9 +21,7 @@
## 解法
-
-
-**方法一:哈希表**
+### 方法一:哈希表
同时遍历两个字符串,算出对应位置字符相同的个数,累加到 $x$ 中,然后将两个字符串出现的字符以及出现的次数分别记录在哈希表 $cnt1$ 和 $cnt2$ 中。
@@ -33,10 +31,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def masterMind(self, solution: str, guess: str) -> List[int]:
@@ -45,10 +39,6 @@ class Solution:
return [x, y - x]
```
-### **Java**
-
-
-
```java
class Solution {
public int[] masterMind(String solution, String guess) {
@@ -69,8 +59,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -89,8 +77,6 @@ public:
};
```
-### **Go**
-
```go
func masterMind(solution string, guess string) []int {
var x, y int
@@ -111,8 +97,6 @@ func masterMind(solution string, guess string) []int {
}
```
-### **JavaScript**
-
```js
/**
* @param {string} solution
@@ -138,10 +122,6 @@ var masterMind = function (solution, guess) {
};
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.15.Master Mind/README_EN.md b/lcci/16.15.Master Mind/README_EN.md
index c0434490e72ad..cbaf67b0ff3fa 100644
--- a/lcci/16.15.Master Mind/README_EN.md
+++ b/lcci/16.15.Master Mind/README_EN.md
@@ -28,7 +28,7 @@
## Solutions
-**Solution 1: Hash Table**
+### Solution 1: Hash Table
We simultaneously traverse both strings, count the number of corresponding characters that are the same, and accumulate them in $x$. Then we record the characters and their frequencies in both strings in hash tables $cnt1$ and $cnt2$, respectively.
@@ -38,8 +38,6 @@ The time complexity is $O(C)$, and the space complexity is $O(C)$. Here, $C=4$ f
-### **Python3**
-
```python
class Solution:
def masterMind(self, solution: str, guess: str) -> List[int]:
@@ -48,8 +46,6 @@ class Solution:
return [x, y - x]
```
-### **Java**
-
```java
class Solution {
public int[] masterMind(String solution, String guess) {
@@ -70,8 +66,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -90,8 +84,6 @@ public:
};
```
-### **Go**
-
```go
func masterMind(solution string, guess string) []int {
var x, y int
@@ -112,8 +104,6 @@ func masterMind(solution string, guess string) []int {
}
```
-### **JavaScript**
-
```js
/**
* @param {string} solution
@@ -139,10 +129,6 @@ var masterMind = function (solution, guess) {
};
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.16.Sub Sort/README.md b/lcci/16.16.Sub Sort/README.md
index 51428b100e948..352c229f0633d 100644
--- a/lcci/16.16.Sub Sort/README.md
+++ b/lcci/16.16.Sub Sort/README.md
@@ -18,9 +18,7 @@
## 解法
-
-
-**方法一:两次遍历**
+### 方法一:两次遍历
我们先从左到右遍历数组 $array$,用 $mx$ 记录遍历过的最大值,如果当前值 $x$ 小于 $mx$,则说明 $x$ 需要被排序,我们将 $x$ 的下标 $i$ 记录为 $right$;否则更新 $mx$。
@@ -32,10 +30,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def subSort(self, array: List[int]) -> List[int]:
@@ -55,10 +49,6 @@ class Solution:
return [left, right]
```
-### **Java**
-
-
-
```java
class Solution {
public int[] subSort(int[] array) {
@@ -84,8 +74,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -112,8 +100,6 @@ public:
};
```
-### **Go**
-
```go
func subSort(array []int) []int {
n := len(array)
@@ -137,8 +123,6 @@ func subSort(array []int) []int {
}
```
-### **TypeScript**
-
```ts
function subSort(array: number[]): number[] {
const n = array.length;
@@ -162,10 +146,6 @@ function subSort(array: number[]): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.16.Sub Sort/README_EN.md b/lcci/16.16.Sub Sort/README_EN.md
index 692ad155908ec..9372eb8221224 100644
--- a/lcci/16.16.Sub Sort/README_EN.md
+++ b/lcci/16.16.Sub Sort/README_EN.md
@@ -21,7 +21,7 @@
## Solutions
-**Solution 1: Two Passes**
+### Solution 1: Two Passes
We first traverse the array $array$ from left to right, and use $mx$ to record the maximum value encountered so far. If the current value $x$ is less than $mx$, it means that $x$ needs to be sorted, and we record the index $i$ of $x$ as $right$; otherwise, update $mx$.
@@ -33,8 +33,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $array$. The
-### **Python3**
-
```python
class Solution:
def subSort(self, array: List[int]) -> List[int]:
@@ -54,8 +52,6 @@ class Solution:
return [left, right]
```
-### **Java**
-
```java
class Solution {
public int[] subSort(int[] array) {
@@ -81,8 +77,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -109,8 +103,6 @@ public:
};
```
-### **Go**
-
```go
func subSort(array []int) []int {
n := len(array)
@@ -134,8 +126,6 @@ func subSort(array []int) []int {
}
```
-### **TypeScript**
-
```ts
function subSort(array: number[]): number[] {
const n = array.length;
@@ -159,10 +149,6 @@ function subSort(array: number[]): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.17.Contiguous Sequence/README.md b/lcci/16.17.Contiguous Sequence/README.md
index 3227ad1ad04fc..f74e8a636de6b 100644
--- a/lcci/16.17.Contiguous Sequence/README.md
+++ b/lcci/16.17.Contiguous Sequence/README.md
@@ -20,9 +20,7 @@
## 解法
-
-
-**方法一:动态规划**
+### 方法一:动态规划
我们定义 $f[i]$ 表示以 $nums[i]$ 结尾的连续子数组的最大和,那么状态转移方程为:
@@ -40,10 +38,6 @@ $$
-### **Python3**
-
-
-
```python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
@@ -54,10 +48,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
public int maxSubArray(int[] nums) {
@@ -71,8 +61,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -87,8 +75,6 @@ public:
};
```
-### **Go**
-
```go
func maxSubArray(nums []int) int {
ans, f := math.MinInt32, math.MinInt32
@@ -100,8 +86,6 @@ func maxSubArray(nums []int) int {
}
```
-### **TypeScript**
-
```ts
function maxSubArray(nums: number[]): number {
let [ans, f] = [-Infinity, -Infinity];
@@ -113,8 +97,6 @@ function maxSubArray(nums: number[]): number {
}
```
-### **JavaScript**
-
```js
/**
* @param {number[]} nums
@@ -130,11 +112,6 @@ var maxSubArray = function (nums) {
};
```
-### **...**
-
-```
-
-
-```
-
+
+
diff --git a/lcci/16.17.Contiguous Sequence/README_EN.md b/lcci/16.17.Contiguous Sequence/README_EN.md
index 145993f009843..3b09c28c5fce8 100644
--- a/lcci/16.17.Contiguous Sequence/README_EN.md
+++ b/lcci/16.17.Contiguous Sequence/README_EN.md
@@ -32,7 +32,7 @@
## Solutions
-**Solution 1: Dynamic Programming**
+### Solution 1: Dynamic Programming
We define $f[i]$ as the maximum sum of a continuous subarray that ends with $nums[i]$. The state transition equation is:
@@ -50,8 +50,6 @@ We notice that $f[i]$ only depends on $f[i-1]$, so we can use a variable $f$ to
-### **Python3**
-
```python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
@@ -62,8 +60,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
public int maxSubArray(int[] nums) {
@@ -77,8 +73,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -93,8 +87,6 @@ public:
};
```
-### **Go**
-
```go
func maxSubArray(nums []int) int {
ans, f := math.MinInt32, math.MinInt32
@@ -106,8 +98,6 @@ func maxSubArray(nums []int) int {
}
```
-### **TypeScript**
-
```ts
function maxSubArray(nums: number[]): number {
let [ans, f] = [-Infinity, -Infinity];
@@ -119,8 +109,6 @@ function maxSubArray(nums: number[]): number {
}
```
-### **JavaScript**
-
```js
/**
* @param {number[]} nums
@@ -136,11 +124,6 @@ var maxSubArray = function (nums) {
};
```
-### **...**
-
-```
-
-
-```
-
+
+
diff --git a/lcci/16.18.Pattern Matching/README.md b/lcci/16.18.Pattern Matching/README.md
index 01bd13688ac55..05fcc2096fadc 100644
--- a/lcci/16.18.Pattern Matching/README.md
+++ b/lcci/16.18.Pattern Matching/README.md
@@ -33,9 +33,7 @@
## 解法
-
-
-**方法一:枚举**
+### 方法一:枚举
我们先统计出模式串 $pattern$ 中 `'a'` 和 `'b'` 的个数,分别为 $cnt[0]$ 和 $cnt[1]$。记字符串 $value$ 的长度为 $n$。
@@ -49,10 +47,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def patternMatching(self, pattern: str, value: str) -> bool:
@@ -88,10 +82,6 @@ class Solution:
return False
```
-### **Java**
-
-
-
```java
class Solution {
private String pattern;
@@ -148,8 +138,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -209,8 +197,6 @@ public:
};
```
-### **Go**
-
```go
func patternMatching(pattern string, value string) bool {
cnt := [2]int{}
@@ -259,8 +245,6 @@ func patternMatching(pattern string, value string) bool {
}
```
-### **TypeScript**
-
```ts
function patternMatching(pattern: string, value: string): boolean {
const cnt: number[] = [0, 0];
@@ -308,10 +292,6 @@ function patternMatching(pattern: string, value: string): boolean {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.18.Pattern Matching/README_EN.md b/lcci/16.18.Pattern Matching/README_EN.md
index 9b9bdebda283f..c3fb745452eb0 100644
--- a/lcci/16.18.Pattern Matching/README_EN.md
+++ b/lcci/16.18.Pattern Matching/README_EN.md
@@ -48,7 +48,7 @@
## Solutions
-**Solution 1: Enumeration**
+### Solution 1: Enumeration
We first count the number of characters `'a'` and `'b'` in the pattern string $pattern$, denoted as $cnt[0]$ and $cnt[1]$, respectively. Let the length of the string $value$ be $n$.
@@ -62,8 +62,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i
-### **Python3**
-
```python
class Solution:
def patternMatching(self, pattern: str, value: str) -> bool:
@@ -99,8 +97,6 @@ class Solution:
return False
```
-### **Java**
-
```java
class Solution {
private String pattern;
@@ -157,8 +153,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -218,8 +212,6 @@ public:
};
```
-### **Go**
-
```go
func patternMatching(pattern string, value string) bool {
cnt := [2]int{}
@@ -268,8 +260,6 @@ func patternMatching(pattern string, value string) bool {
}
```
-### **TypeScript**
-
```ts
function patternMatching(pattern: string, value: string): boolean {
const cnt: number[] = [0, 0];
@@ -317,10 +307,6 @@ function patternMatching(pattern: string, value: string): boolean {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.19.Pond Sizes/README.md b/lcci/16.19.Pond Sizes/README.md
index 123ec12a81964..0da952d32f000 100644
--- a/lcci/16.19.Pond Sizes/README.md
+++ b/lcci/16.19.Pond Sizes/README.md
@@ -24,9 +24,7 @@
## 解法
-
-
-**方法一:DFS**
+### 方法一:DFS
我们可以遍历整数矩阵 $land$ 中的每个点 $(i, j)$,如果该点的值为 $0$,则从该点开始进行深度优先搜索,直到搜索到的点的值不为 $0$,则停止搜索,此时搜索到的点的个数即为池塘的大小,将其加入答案数组中。
@@ -38,10 +36,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def pondSizes(self, land: List[List[int]]) -> List[int]:
@@ -58,10 +52,6 @@ class Solution:
return sorted(dfs(i, j) for i in range(m) for j in range(n) if land[i][j] == 0)
```
-### **Java**
-
-
-
```java
class Solution {
private int m;
@@ -98,8 +88,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -131,8 +119,6 @@ public:
};
```
-### **Go**
-
```go
func pondSizes(land [][]int) (ans []int) {
m, n := len(land), len(land[0])
@@ -161,8 +147,6 @@ func pondSizes(land [][]int) (ans []int) {
}
```
-### **TypeScript**
-
```ts
function pondSizes(land: number[][]): number[] {
const m = land.length;
@@ -192,10 +176,6 @@ function pondSizes(land: number[][]): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.19.Pond Sizes/README_EN.md b/lcci/16.19.Pond Sizes/README_EN.md
index 9c21c54fa2c84..f58c8d83e28db 100644
--- a/lcci/16.19.Pond Sizes/README_EN.md
+++ b/lcci/16.19.Pond Sizes/README_EN.md
@@ -37,7 +37,7 @@
## Solutions
-**Solution 1: DFS**
+### Solution 1: DFS
We can traverse each point $(i, j)$ in the integer matrix $land$. If the value of the point is $0$, we start a depth-first search from this point until we reach a point with a non-zero value. The number of points searched during this process is the size of the pond, which is added to the answer array.
@@ -49,8 +49,6 @@ The time complexity is $O(m \times n \times \log (m \times n))$, and the space c
-### **Python3**
-
```python
class Solution:
def pondSizes(self, land: List[List[int]]) -> List[int]:
@@ -67,8 +65,6 @@ class Solution:
return sorted(dfs(i, j) for i in range(m) for j in range(n) if land[i][j] == 0)
```
-### **Java**
-
```java
class Solution {
private int m;
@@ -105,8 +101,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -138,8 +132,6 @@ public:
};
```
-### **Go**
-
```go
func pondSizes(land [][]int) (ans []int) {
m, n := len(land), len(land[0])
@@ -168,8 +160,6 @@ func pondSizes(land [][]int) (ans []int) {
}
```
-### **TypeScript**
-
```ts
function pondSizes(land: number[][]): number[] {
const m = land.length;
@@ -199,10 +189,6 @@ function pondSizes(land: number[][]): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.20.T9/README.md b/lcci/16.20.T9/README.md
index 99b622ec17f75..2d68a027fe195 100644
--- a/lcci/16.20.T9/README.md
+++ b/lcci/16.20.T9/README.md
@@ -25,9 +25,7 @@
## 解法
-
-
-**方法一:逆向思维**
+### 方法一:逆向思维
我们考虑一种正向的解法,遍历字符串 $num$ 中的每个数字,将其映射到对应的字母,然后将所有的字母组合起来,得到所有可能的单词,再与给定的单词列表进行比较,若单词在列表中,则将其加入答案。这种解法的时间复杂度为 $O(4^n)$,其中 $n$ 为字符串 $num$ 的长度,显然会超时。
@@ -37,10 +35,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
@@ -51,17 +45,6 @@ class Solution:
return [w for w in words if check(w)]
```
-```python
-class Solution:
- def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
- trans = str.maketrans(ascii_lowercase, "22233344455566677778889999")
- return [w for w in words if w.translate(trans) == num]
-```
-
-### **Java**
-
-
-
```java
class Solution {
public List getValidT9Words(String num, String[] words) {
@@ -89,8 +72,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -118,8 +99,6 @@ public:
};
```
-### **Go**
-
```go
func getValidT9Words(num string, words []string) (ans []string) {
s := "22233344455566677778889999"
@@ -143,8 +122,6 @@ func getValidT9Words(num string, words []string) (ans []string) {
}
```
-### **TypeScript**
-
```ts
function getValidT9Words(num: string, words: string[]): string[] {
const s = '22233344455566677778889999';
@@ -170,10 +147,19 @@ function getValidT9Words(num: string, words: string[]): string[] {
}
```
-### **...**
+
+
+### 方法二
-```
+
+```python
+class Solution:
+ def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
+ trans = str.maketrans(ascii_lowercase, "22233344455566677778889999")
+ return [w for w in words if w.translate(trans) == num]
```
+
+
diff --git a/lcci/16.20.T9/README_EN.md b/lcci/16.20.T9/README_EN.md
index 34276644e7d73..84af97d6a7b77 100644
--- a/lcci/16.20.T9/README_EN.md
+++ b/lcci/16.20.T9/README_EN.md
@@ -31,7 +31,7 @@
## Solutions
-**Solution 1: Reverse Thinking**
+### Solution 1: Reverse Thinking
We consider a forward solution, which traverses each digit in the string $num$, maps it to the corresponding letter, combines all the letters to obtain all possible words, and then compares them with the given word list. If the word is in the list, it is added to the answer. The time complexity of this solution is $O(4^n)$, where $n$ is the length of the string $num$, which will obviously time out.
@@ -41,8 +41,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(C)$. Here
-### **Python3**
-
```python
class Solution:
def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
@@ -53,15 +51,6 @@ class Solution:
return [w for w in words if check(w)]
```
-```python
-class Solution:
- def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
- trans = str.maketrans(ascii_lowercase, "22233344455566677778889999")
- return [w for w in words if w.translate(trans) == num]
-```
-
-### **Java**
-
```java
class Solution {
public List getValidT9Words(String num, String[] words) {
@@ -89,8 +78,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -118,8 +105,6 @@ public:
};
```
-### **Go**
-
```go
func getValidT9Words(num string, words []string) (ans []string) {
s := "22233344455566677778889999"
@@ -143,8 +128,6 @@ func getValidT9Words(num string, words []string) (ans []string) {
}
```
-### **TypeScript**
-
```ts
function getValidT9Words(num: string, words: string[]): string[] {
const s = '22233344455566677778889999';
@@ -170,10 +153,19 @@ function getValidT9Words(num: string, words: string[]): string[] {
}
```
-### **...**
+
-```
+### Solution 2
+
+
+```python
+class Solution:
+ def getValidT9Words(self, num: str, words: List[str]) -> List[str]:
+ trans = str.maketrans(ascii_lowercase, "22233344455566677778889999")
+ return [w for w in words if w.translate(trans) == num]
```
+
+
diff --git a/lcci/16.21.Sum Swap/README.md b/lcci/16.21.Sum Swap/README.md
index 2420cf380664d..b70950be66aa2 100644
--- a/lcci/16.21.Sum Swap/README.md
+++ b/lcci/16.21.Sum Swap/README.md
@@ -28,9 +28,7 @@
## 解法
-
-
-**方法一:哈希表**
+### 方法一:哈希表
我们先求出两个数组的和,然后计算两个数组和的差值 $diff$。如果 $diff$ 为奇数,则说明两个数组的和不可能相等,直接返回空数组。
@@ -40,10 +38,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def findSwapValues(self, array1: List[int], array2: List[int]) -> List[int]:
@@ -58,10 +52,6 @@ class Solution:
return []
```
-### **Java**
-
-
-
```java
class Solution {
public int[] findSwapValues(int[] array1, int[] array2) {
@@ -90,8 +80,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -115,8 +103,6 @@ public:
};
```
-### **Go**
-
```go
func findSwapValues(array1 []int, array2 []int) []int {
s1, s2 := 0, 0
@@ -142,8 +128,6 @@ func findSwapValues(array1 []int, array2 []int) []int {
}
```
-### **TypeScript**
-
```ts
function findSwapValues(array1: number[], array2: number[]): number[] {
const s1 = array1.reduce((a, b) => a + b, 0);
@@ -164,10 +148,6 @@ function findSwapValues(array1: number[], array2: number[]): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.21.Sum Swap/README_EN.md b/lcci/16.21.Sum Swap/README_EN.md
index b21835b493e3b..1e96bc3427299 100644
--- a/lcci/16.21.Sum Swap/README_EN.md
+++ b/lcci/16.21.Sum Swap/README_EN.md
@@ -34,7 +34,7 @@
## Solutions
-**Solution 1: Hash Table**
+### Solution 1: Hash Table
We first calculate the sum of the two arrays, and then calculate the difference $diff$ between the sums. If $diff$ is odd, it means that the sums of the two arrays cannot be equal, so we directly return an empty array.
@@ -44,8 +44,6 @@ The time complexity is $O(m + n)$, and the space complexity is $O(n)$. Here, $m$
-### **Python3**
-
```python
class Solution:
def findSwapValues(self, array1: List[int], array2: List[int]) -> List[int]:
@@ -60,8 +58,6 @@ class Solution:
return []
```
-### **Java**
-
```java
class Solution {
public int[] findSwapValues(int[] array1, int[] array2) {
@@ -90,8 +86,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -115,8 +109,6 @@ public:
};
```
-### **Go**
-
```go
func findSwapValues(array1 []int, array2 []int) []int {
s1, s2 := 0, 0
@@ -142,8 +134,6 @@ func findSwapValues(array1 []int, array2 []int) []int {
}
```
-### **TypeScript**
-
```ts
function findSwapValues(array1: number[], array2: number[]): number[] {
const s1 = array1.reduce((a, b) => a + b, 0);
@@ -164,10 +154,6 @@ function findSwapValues(array1: number[], array2: number[]): number[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.22.Langtons Ant/README.md b/lcci/16.22.Langtons Ant/README.md
index a4bf261a47be2..b5bf1233c67fb 100644
--- a/lcci/16.22.Langtons Ant/README.md
+++ b/lcci/16.22.Langtons Ant/README.md
@@ -39,9 +39,7 @@
## 解法
-
-
-**方法一:哈希表 + 模拟**
+### 方法一:哈希表 + 模拟
我们使用哈希表 $black$ 来记录所有黑色方格的位置,哈希表 $dirs$ 来记录蚂蚁的四个方向。我们使用变量 $x, y$ 来记录蚂蚁的位置,使用变量 $p$ 来记录蚂蚁的方向。我们使用变量 $x1, y1, x2, y2$ 来记录所有黑色方格的最小横坐标、最小纵坐标、最大横坐标、最大纵坐标。
@@ -53,10 +51,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def printKMoves(self, K: int) -> List[str]:
@@ -87,10 +81,6 @@ class Solution:
return ["".join(row) for row in g]
```
-### **Java**
-
-
-
```java
class Solution {
public List printKMoves(int K) {
@@ -135,8 +125,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -173,8 +161,6 @@ public:
};
```
-### **Go**
-
```go
func printKMoves(K int) []string {
var x1, y1, x2, y2, x, y, p int
@@ -220,10 +206,6 @@ func printKMoves(K int) []string {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.22.Langtons Ant/README_EN.md b/lcci/16.22.Langtons Ant/README_EN.md
index 2c5af223224d4..acb936ed846be 100644
--- a/lcci/16.22.Langtons Ant/README_EN.md
+++ b/lcci/16.22.Langtons Ant/README_EN.md
@@ -59,7 +59,7 @@
## Solutions
-**Solution 1: Hash Table + Simulation**
+### Solution 1: Hash Table + Simulation
We use a hash table $black$ to record the positions of all black squares, and a hash table $dirs$ to record the four directions of the ant. We use variables $x, y$ to record the position of the ant, and variable $p$ to record the direction of the ant. We use variables $x1, y1, x2, y2$ to record the minimum horizontal coordinate, minimum vertical coordinate, maximum horizontal coordinate, and maximum vertical coordinate of all black squares.
@@ -71,8 +71,6 @@ The time complexity is $O(K)$, and the space complexity is $O(K)$. Here, $K$ is
-### **Python3**
-
```python
class Solution:
def printKMoves(self, K: int) -> List[str]:
@@ -103,8 +101,6 @@ class Solution:
return ["".join(row) for row in g]
```
-### **Java**
-
```java
class Solution {
public List printKMoves(int K) {
@@ -149,8 +145,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -187,8 +181,6 @@ public:
};
```
-### **Go**
-
```go
func printKMoves(K int) []string {
var x1, y1, x2, y2, x, y, p int
@@ -234,10 +226,6 @@ func printKMoves(K int) []string {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.24.Pairs With Sum/README.md b/lcci/16.24.Pairs With Sum/README.md
index 40314066862e3..e8e672431f3a4 100644
--- a/lcci/16.24.Pairs With Sum/README.md
+++ b/lcci/16.24.Pairs With Sum/README.md
@@ -20,9 +20,7 @@
## 解法
-
-
-**方法一:哈希表**
+### 方法一:哈希表
我们可以使用哈希表来存储数组中的元素,键为数组中的元素,值为该元素出现的次数。
@@ -34,10 +32,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def pairSums(self, nums: List[int], target: int) -> List[List[int]]:
@@ -53,10 +47,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
public List> pairSums(int[] nums, int target) {
@@ -78,8 +68,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -100,8 +88,6 @@ public:
};
```
-### **Go**
-
```go
func pairSums(nums []int, target int) (ans [][]int) {
cnt := map[int]int{}
@@ -118,8 +104,6 @@ func pairSums(nums []int, target int) (ans [][]int) {
}
```
-### **TypeScript**
-
```ts
function pairSums(nums: number[], target: number): number[][] {
const cnt = new Map();
@@ -142,10 +126,6 @@ function pairSums(nums: number[], target: number): number[][] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.24.Pairs With Sum/README_EN.md b/lcci/16.24.Pairs With Sum/README_EN.md
index 88fac50820e19..d255145ccf12e 100644
--- a/lcci/16.24.Pairs With Sum/README_EN.md
+++ b/lcci/16.24.Pairs With Sum/README_EN.md
@@ -24,7 +24,7 @@
## Solutions
-**Solution 1: Hash Table**
+### Solution 1: Hash Table
We can use a hash table to store the elements in the array, with the keys being the elements in the array and the values being the number of times the element appears.
@@ -36,8 +36,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is
-### **Python3**
-
```python
class Solution:
def pairSums(self, nums: List[int], target: int) -> List[List[int]]:
@@ -53,8 +51,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
public List> pairSums(int[] nums, int target) {
@@ -76,8 +72,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -98,8 +92,6 @@ public:
};
```
-### **Go**
-
```go
func pairSums(nums []int, target int) (ans [][]int) {
cnt := map[int]int{}
@@ -116,8 +108,6 @@ func pairSums(nums []int, target int) (ans [][]int) {
}
```
-### **TypeScript**
-
```ts
function pairSums(nums: number[], target: number): number[][] {
const cnt = new Map();
@@ -140,10 +130,6 @@ function pairSums(nums: number[], target: number): number[][] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.25.LRU Cache/README.md b/lcci/16.25.LRU Cache/README.md
index 011953ac07f1f..df65a35f4c41f 100644
--- a/lcci/16.25.LRU Cache/README.md
+++ b/lcci/16.25.LRU Cache/README.md
@@ -29,50 +29,10 @@ cache.get(4); // 返回 4
## 解法
-
-
-“哈希表 + 双向链表”实现。其中:
-
-- 双向链表按照被使用的顺序存储 kv 键值对,靠近头部的 kv 键值对是最近使用的,而靠近尾部的键值对是最久未使用的。
-- 哈希表通过缓存的 key 映射到双向链表中的位置。我们可以在 `O(1)` 时间内定位到缓存的 key 所对应的 value 在链表中的位置。
-
-对于 `get` 操作,判断 key 是否存在哈希表中:
-
-- 若不存在,返回 -1
-- 若存在,则 key 对应的节点 node 是最近使用的节点。将该节点移动到双向链表的头部,最后返回该节点的值即可。
-
-对于 `put` 操作,同样先判断 key 是否存在哈希表中:
-
-- 若不存在,则创建一个新的 node 节点,放入哈希表中。然后在双向链表的头部添加该节点。接着判断双向链表节点数是否超过 capacity。若超过,则删除双向链表的尾部节点,以及在哈希表中对应的项。
-- 若存在,则更新 node 节点的值,然后该节点移动到双向链表的头部。
-
-双向链表节点(哈希表的 value)的结构如下:
-
-```java
-class Node {
- int key;
- int value;
- Node prev;
- Node next;
- Node() {
- }
- Node(int key, int value) {
- this.key = key;
- this.value = value;
- }
-}
-```
-
-你可能会问,哈希表的 value 为何还要存放 key?
-
-这是因为,双向链表有一个删除尾节点的操作。我们定位到双向链表的尾节点,在链表中删除之后,还要找到该尾节点在哈希表中的位置,因此需要根据 value 中存放的 key,定位到哈希表的数据项,然后将其删除。
+### 方法一
-### **Python3**
-
-
-
```python
class Node:
def __init__(self, key=0, value=0):
@@ -140,10 +100,6 @@ class LRUCache:
# obj.put(key,value)
```
-### **Java**
-
-
-
```java
class LRUCache {
class Node {
@@ -233,10 +189,6 @@ class LRUCache {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.25.LRU Cache/README_EN.md b/lcci/16.25.LRU Cache/README_EN.md
index fde578d194802..a1f26d93b1008 100644
--- a/lcci/16.25.LRU Cache/README_EN.md
+++ b/lcci/16.25.LRU Cache/README_EN.md
@@ -42,9 +42,9 @@ cache.get(4); // returns 4
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Node:
@@ -113,8 +113,6 @@ class LRUCache:
# obj.put(key,value)
```
-### **Java**
-
```java
class LRUCache {
class Node {
@@ -204,10 +202,6 @@ class LRUCache {
*/
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.26.Calculator/README.md b/lcci/16.26.Calculator/README.md
index eed6523adfa73..ba7eaed847d1d 100644
--- a/lcci/16.26.Calculator/README.md
+++ b/lcci/16.26.Calculator/README.md
@@ -27,9 +27,7 @@
## 解法
-
-
-**方法一:栈**
+### 方法一:栈
我们可以用一个栈来保存数字,每次遇到运算符时,就将数字压入栈中。对于加减法,由于其优先级最低,我们可以直接将数字压入栈中;对于乘除法,由于其优先级较高,我们需要将栈顶元素取出,与当前数字进行乘除运算,再将结果压入栈中。
@@ -39,10 +37,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def calculate(self, s: str) -> int:
@@ -68,10 +62,6 @@ class Solution:
return sum(stk)
```
-### **Java**
-
-
-
```java
class Solution {
public int calculate(String s) {
@@ -104,8 +94,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -147,8 +135,6 @@ public:
};
```
-### **Go**
-
```go
func calculate(s string) (ans int) {
n := len(s)
@@ -181,8 +167,6 @@ func calculate(s string) (ans int) {
}
```
-### **TypeScript**
-
```ts
function calculate(s: string): number {
const n = s.length;
@@ -215,10 +199,6 @@ function calculate(s: string): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/16.26.Calculator/README_EN.md b/lcci/16.26.Calculator/README_EN.md
index 47826a1016c3e..cb57d9bbebfcb 100644
--- a/lcci/16.26.Calculator/README_EN.md
+++ b/lcci/16.26.Calculator/README_EN.md
@@ -37,9 +37,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -66,8 +66,6 @@ class Solution:
return sum(stk)
```
-### **Java**
-
```java
class Solution {
public int calculate(String s) {
@@ -100,8 +98,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -143,8 +139,6 @@ public:
};
```
-### **Go**
-
```go
func calculate(s string) (ans int) {
n := len(s)
@@ -177,8 +171,6 @@ func calculate(s string) (ans int) {
}
```
-### **TypeScript**
-
```ts
function calculate(s: string): number {
const n = s.length;
@@ -211,10 +203,6 @@ function calculate(s: string): number {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.01.Add Without Plus/README.md b/lcci/17.01.Add Without Plus/README.md
index 63b60c8164278..dde30d25c3476 100644
--- a/lcci/17.01.Add Without Plus/README.md
+++ b/lcci/17.01.Add Without Plus/README.md
@@ -24,22 +24,10 @@
## 解法
-
+### 方法一
-### **Python3**
-
-
-
-```python
-
-```
-
-### **Java**
-
-
-
```java
class Solution {
public int add(int a, int b) {
@@ -55,10 +43,6 @@ class Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.01.Add Without Plus/README_EN.md b/lcci/17.01.Add Without Plus/README_EN.md
index bb6b16e19fa82..7b5d49f2e1a14 100644
--- a/lcci/17.01.Add Without Plus/README_EN.md
+++ b/lcci/17.01.Add Without Plus/README_EN.md
@@ -25,15 +25,9 @@
## Solutions
-
-
-### **Python3**
-
-```python
+### Solution 1
-```
-
-### **Java**
+
```java
class Solution {
@@ -50,10 +44,6 @@ class Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.04.Missing Number/README.md b/lcci/17.04.Missing Number/README.md
index 5f6b05adf6f39..77ec170e6d1aa 100644
--- a/lcci/17.04.Missing Number/README.md
+++ b/lcci/17.04.Missing Number/README.md
@@ -24,9 +24,7 @@
## 解法
-
-
-**方法一:排序**
+### 方法一:排序
我们可以先对数组 $nums$ 进行排序,然后遍历排序后的数组,判断当前元素是否等于其下标,若不等,则返回下标即可。
@@ -34,24 +32,8 @@
时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。
-**方法二:求和**
-
-我们可以先求出 $0$ 到 $n$ 的和,然后遍历数组 $nums$,将数组中的元素依次减去,最后剩下的值即为缺失的数字。
-
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。
-
-**方法三:位运算**
-
-我们可以使用异或运算,将 $0$ 到 $n$ 的所有数与数组 $nums$ 中的数进行异或运算,最后剩下的值即为缺失的数字。
-
-时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。
-
-### **Python3**
-
-
-
```python
class Solution:
def missingNumber(self, nums: List[int]) -> int:
@@ -62,25 +44,6 @@ class Solution:
return len(nums)
```
-```python
-class Solution:
- def missingNumber(self, nums: List[int]) -> int:
- return sum(range(len(nums) + 1)) - sum(nums)
-```
-
-```python
-class Solution:
- def missingNumber(self, nums: List[int]) -> int:
- ans = 0
- for i, x in enumerate(nums, 1):
- ans ^= i ^ x
- return ans
-```
-
-### **Java**
-
-
-
```java
class Solution {
public int missingNumber(int[] nums) {
@@ -96,33 +59,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int missingNumber(int[] nums) {
- int n = nums.length;
- int ans = n;
- for (int i = 0; i < n; ++i) {
- ans += i - nums[i];
- }
- return ans;
- }
-}
-```
-
-```java
-class Solution {
- public int missingNumber(int[] nums) {
- int ans = 0;
- for (int i = 1; i <= nums.length; ++i) {
- ans ^= i ^ nums[i - 1];
- }
- return ans;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -139,35 +75,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- int missingNumber(vector& nums) {
- int n = nums.size();
- int ans = n;
- for (int i = 0; i < n; ++i) {
- ans += i - nums[i];
- }
- return ans;
- }
-};
-```
-
-```cpp
-class Solution {
-public:
- int missingNumber(vector& nums) {
- int ans = 0;
- for (int i = 1; i <= nums.size(); ++i) {
- ans ^= i ^ nums[i - 1];
- }
- return ans;
- }
-};
-```
-
-### **Go**
-
```go
func missingNumber(nums []int) int {
sort.Ints(nums)
@@ -180,27 +87,21 @@ func missingNumber(nums []int) int {
}
```
-```go
-func missingNumber(nums []int) (ans int) {
- ans = len(nums)
- for i, x := range nums {
- ans += i - x
- }
- return
-}
-```
-
-```go
-func missingNumber(nums []int) (ans int) {
- for i, x := range nums {
- ans ^= (i + 1) ^ x
- }
- return
+```rust
+impl Solution {
+ pub fn missing_number(mut nums: Vec) -> i32 {
+ nums.sort();
+ let n = nums.len() as i32;
+ for i in 0..n {
+ if i != nums[i as usize] {
+ return i;
+ }
+ }
+ n
+ }
}
```
-### **JavaScript**
-
```js
/**
* @param {number[]} nums
@@ -218,49 +119,56 @@ var missingNumber = function (nums) {
};
```
-```js
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var missingNumber = function (nums) {
- const n = nums.length;
- let ans = n;
- for (let i = 0; i < n; ++i) {
- ans += i - nums[i];
- }
- return ans;
-};
+
+
+### 方法二:求和
+
+我们可以先求出 $0$ 到 $n$ 的和,然后遍历数组 $nums$,将数组中的元素依次减去,最后剩下的值即为缺失的数字。
+
+时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。
+
+
+
+```python
+class Solution:
+ def missingNumber(self, nums: List[int]) -> int:
+ return sum(range(len(nums) + 1)) - sum(nums)
```
-```js
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var missingNumber = function (nums) {
- let ans = 0;
- for (let i = 1; i <= nums.length; ++i) {
- ans ^= i ^ nums[i - 1];
+```java
+class Solution {
+ public int missingNumber(int[] nums) {
+ int n = nums.length;
+ int ans = n;
+ for (int i = 0; i < n; ++i) {
+ ans += i - nums[i];
+ }
+ return ans;
}
- return ans;
-};
+}
```
-### **Rust**
-
-```rust
-impl Solution {
- pub fn missing_number(mut nums: Vec) -> i32 {
- nums.sort();
- let n = nums.len() as i32;
- for i in 0..n {
- if i != nums[i as usize] {
- return i;
- }
+```cpp
+class Solution {
+public:
+ int missingNumber(vector& nums) {
+ int n = nums.size();
+ int ans = n;
+ for (int i = 0; i < n; ++i) {
+ ans += i - nums[i];
}
- n
+ return ans;
}
+};
+```
+
+```go
+func missingNumber(nums []int) (ans int) {
+ ans = len(nums)
+ for i, x := range nums {
+ ans += i - x
+ }
+ return
}
```
@@ -283,6 +191,74 @@ impl Solution {
}
```
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var missingNumber = function (nums) {
+ const n = nums.length;
+ let ans = n;
+ for (let i = 0; i < n; ++i) {
+ ans += i - nums[i];
+ }
+ return ans;
+};
+```
+
+
+
+### 方法三:位运算
+
+我们可以使用异或运算,将 $0$ 到 $n$ 的所有数与数组 $nums$ 中的数进行异或运算,最后剩下的值即为缺失的数字。
+
+时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。
+
+
+
+```python
+class Solution:
+ def missingNumber(self, nums: List[int]) -> int:
+ ans = 0
+ for i, x in enumerate(nums, 1):
+ ans ^= i ^ x
+ return ans
+```
+
+```java
+class Solution {
+ public int missingNumber(int[] nums) {
+ int ans = 0;
+ for (int i = 1; i <= nums.length; ++i) {
+ ans ^= i ^ nums[i - 1];
+ }
+ return ans;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ int missingNumber(vector& nums) {
+ int ans = 0;
+ for (int i = 1; i <= nums.size(); ++i) {
+ ans ^= i ^ nums[i - 1];
+ }
+ return ans;
+ }
+};
+```
+
+```go
+func missingNumber(nums []int) (ans int) {
+ for i, x := range nums {
+ ans ^= (i + 1) ^ x
+ }
+ return
+}
+```
+
```rust
impl Solution {
pub fn missing_number(nums: Vec) -> i32 {
@@ -296,10 +272,20 @@ impl Solution {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var missingNumber = function (nums) {
+ let ans = 0;
+ for (let i = 1; i <= nums.length; ++i) {
+ ans ^= i ^ nums[i - 1];
+ }
+ return ans;
+};
```
+
+
diff --git a/lcci/17.04.Missing Number/README_EN.md b/lcci/17.04.Missing Number/README_EN.md
index 8eebd0daaf96f..8d0c402b9388e 100644
--- a/lcci/17.04.Missing Number/README_EN.md
+++ b/lcci/17.04.Missing Number/README_EN.md
@@ -30,9 +30,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -44,23 +44,6 @@ class Solution:
return len(nums)
```
-```python
-class Solution:
- def missingNumber(self, nums: List[int]) -> int:
- return sum(range(len(nums) + 1)) - sum(nums)
-```
-
-```python
-class Solution:
- def missingNumber(self, nums: List[int]) -> int:
- ans = 0
- for i, x in enumerate(nums, 1):
- ans ^= i ^ x
- return ans
-```
-
-### **Java**
-
```java
class Solution {
public int missingNumber(int[] nums) {
@@ -76,33 +59,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int missingNumber(int[] nums) {
- int n = nums.length;
- int ans = n;
- for (int i = 0; i < n; ++i) {
- ans += i - nums[i];
- }
- return ans;
- }
-}
-```
-
-```java
-class Solution {
- public int missingNumber(int[] nums) {
- int ans = 0;
- for (int i = 1; i <= nums.length; ++i) {
- ans ^= i ^ nums[i - 1];
- }
- return ans;
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -119,35 +75,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- int missingNumber(vector& nums) {
- int n = nums.size();
- int ans = n;
- for (int i = 0; i < n; ++i) {
- ans += i - nums[i];
- }
- return ans;
- }
-};
-```
-
-```cpp
-class Solution {
-public:
- int missingNumber(vector& nums) {
- int ans = 0;
- for (int i = 1; i <= nums.size(); ++i) {
- ans ^= i ^ nums[i - 1];
- }
- return ans;
- }
-};
-```
-
-### **Go**
-
```go
func missingNumber(nums []int) int {
sort.Ints(nums)
@@ -160,27 +87,21 @@ func missingNumber(nums []int) int {
}
```
-```go
-func missingNumber(nums []int) (ans int) {
- ans = len(nums)
- for i, x := range nums {
- ans += i - x
- }
- return
-}
-```
-
-```go
-func missingNumber(nums []int) (ans int) {
- for i, x := range nums {
- ans ^= (i + 1) ^ x
- }
- return
+```rust
+impl Solution {
+ pub fn missing_number(mut nums: Vec) -> i32 {
+ nums.sort();
+ let n = nums.len() as i32;
+ for i in 0..n {
+ if i != nums[i as usize] {
+ return i;
+ }
+ }
+ n
+ }
}
```
-### **JavaScript**
-
```js
/**
* @param {number[]} nums
@@ -198,49 +119,52 @@ var missingNumber = function (nums) {
};
```
-```js
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var missingNumber = function (nums) {
- const n = nums.length;
- let ans = n;
- for (let i = 0; i < n; ++i) {
- ans += i - nums[i];
- }
- return ans;
-};
+
+
+### Solution 2
+
+
+
+```python
+class Solution:
+ def missingNumber(self, nums: List[int]) -> int:
+ return sum(range(len(nums) + 1)) - sum(nums)
```
-```js
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var missingNumber = function (nums) {
- let ans = 0;
- for (let i = 1; i <= nums.length; ++i) {
- ans ^= i ^ nums[i - 1];
+```java
+class Solution {
+ public int missingNumber(int[] nums) {
+ int n = nums.length;
+ int ans = n;
+ for (int i = 0; i < n; ++i) {
+ ans += i - nums[i];
+ }
+ return ans;
}
- return ans;
-};
+}
```
-### **Rust**
-
-```rust
-impl Solution {
- pub fn missing_number(mut nums: Vec) -> i32 {
- nums.sort();
- let n = nums.len() as i32;
- for i in 0..n {
- if i != nums[i as usize] {
- return i;
- }
+```cpp
+class Solution {
+public:
+ int missingNumber(vector& nums) {
+ int n = nums.size();
+ int ans = n;
+ for (int i = 0; i < n; ++i) {
+ ans += i - nums[i];
}
- n
+ return ans;
}
+};
+```
+
+```go
+func missingNumber(nums []int) (ans int) {
+ ans = len(nums)
+ for i, x := range nums {
+ ans += i - x
+ }
+ return
}
```
@@ -263,6 +187,70 @@ impl Solution {
}
```
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var missingNumber = function (nums) {
+ const n = nums.length;
+ let ans = n;
+ for (let i = 0; i < n; ++i) {
+ ans += i - nums[i];
+ }
+ return ans;
+};
+```
+
+
+
+### Solution 3
+
+
+
+```python
+class Solution:
+ def missingNumber(self, nums: List[int]) -> int:
+ ans = 0
+ for i, x in enumerate(nums, 1):
+ ans ^= i ^ x
+ return ans
+```
+
+```java
+class Solution {
+ public int missingNumber(int[] nums) {
+ int ans = 0;
+ for (int i = 1; i <= nums.length; ++i) {
+ ans ^= i ^ nums[i - 1];
+ }
+ return ans;
+ }
+}
+```
+
+```cpp
+class Solution {
+public:
+ int missingNumber(vector& nums) {
+ int ans = 0;
+ for (int i = 1; i <= nums.size(); ++i) {
+ ans ^= i ^ nums[i - 1];
+ }
+ return ans;
+ }
+};
+```
+
+```go
+func missingNumber(nums []int) (ans int) {
+ for i, x := range nums {
+ ans ^= (i + 1) ^ x
+ }
+ return
+}
+```
+
```rust
impl Solution {
pub fn missing_number(nums: Vec) -> i32 {
@@ -276,10 +264,20 @@ impl Solution {
}
```
-### **...**
-
-```
-
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var missingNumber = function (nums) {
+ let ans = 0;
+ for (let i = 1; i <= nums.length; ++i) {
+ ans ^= i ^ nums[i - 1];
+ }
+ return ans;
+};
```
+
+
diff --git a/lcci/17.05.Find Longest Subarray/README.md b/lcci/17.05.Find Longest Subarray/README.md
index 1ded3de3c4806..20ad28c2b6c34 100644
--- a/lcci/17.05.Find Longest Subarray/README.md
+++ b/lcci/17.05.Find Longest Subarray/README.md
@@ -31,9 +31,7 @@
## 解法
-
-
-**方法一:前缀和 + 哈希表**
+### 方法一:前缀和 + 哈希表
题目要求找到最长的子数组,且包含的字符和数字的个数相同。我们可以将字符看作 $1$,数字看作 $-1$,那么问题就转化为:求最长的子数组,使得该子数组的和为 $0$。
@@ -50,10 +48,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def findLongestSubarray(self, array: List[str]) -> List[str]:
@@ -70,10 +64,6 @@ class Solution:
return array[k : k + mx]
```
-### **Java**
-
-
-
```java
class Solution {
public String[] findLongestSubarray(String[] array) {
@@ -99,8 +89,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -124,8 +112,6 @@ public:
};
```
-### **Go**
-
```go
func findLongestSubarray(array []string) []string {
vis := map[int]int{0: -1}
@@ -149,8 +135,6 @@ func findLongestSubarray(array []string) []string {
}
```
-### **TypeScript**
-
```ts
function findLongestSubarray(array: string[]): string[] {
const vis = new Map();
@@ -174,10 +158,6 @@ function findLongestSubarray(array: string[]): string[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.05.Find Longest Subarray/README_EN.md b/lcci/17.05.Find Longest Subarray/README_EN.md
index 34e5c01e63d8b..104402b32629d 100644
--- a/lcci/17.05.Find Longest Subarray/README_EN.md
+++ b/lcci/17.05.Find Longest Subarray/README_EN.md
@@ -40,9 +40,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -60,8 +60,6 @@ class Solution:
return array[k : k + mx]
```
-### **Java**
-
```java
class Solution {
public String[] findLongestSubarray(String[] array) {
@@ -87,8 +85,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -112,8 +108,6 @@ public:
};
```
-### **Go**
-
```go
func findLongestSubarray(array []string) []string {
vis := map[int]int{0: -1}
@@ -137,8 +131,6 @@ func findLongestSubarray(array []string) []string {
}
```
-### **TypeScript**
-
```ts
function findLongestSubarray(array: string[]): string[] {
const vis = new Map();
@@ -162,10 +154,6 @@ function findLongestSubarray(array: string[]): string[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.06.Number Of 2s In Range/README.md b/lcci/17.06.Number Of 2s In Range/README.md
index 6e8d1f7f3a2b9..9e1cbd50d5a41 100644
--- a/lcci/17.06.Number Of 2s In Range/README.md
+++ b/lcci/17.06.Number Of 2s In Range/README.md
@@ -18,9 +18,7 @@
## 解法
-
-
-**方法一:数位 DP**
+### 方法一:数位 DP
这道题实际上是求在给定区间 $[l,..r]$ 中,数字中出现 $2$ 个数。个数与数的位数以及每一位上的数字有关。我们可以用数位 DP 的思路来解决这道题。数位 DP 中,数的大小对复杂度的影响很小。
@@ -53,10 +51,6 @@ $$
-### **Python3**
-
-
-
```python
class Solution:
def numberOf2sInRange(self, n: int) -> int:
@@ -79,10 +73,6 @@ class Solution:
return dfs(l, 0, True)
```
-### **Java**
-
-
-
```java
class Solution {
private int[] a = new int[12];
@@ -120,8 +110,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -158,8 +146,6 @@ public:
};
```
-### **Go**
-
```go
func numberOf2sInRange(n int) int {
a := make([]int, 12)
@@ -205,10 +191,6 @@ func numberOf2sInRange(n int) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.06.Number Of 2s In Range/README_EN.md b/lcci/17.06.Number Of 2s In Range/README_EN.md
index fcfefc419f9be..8f34357da127a 100644
--- a/lcci/17.06.Number Of 2s In Range/README_EN.md
+++ b/lcci/17.06.Number Of 2s In Range/README_EN.md
@@ -21,9 +21,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -47,8 +47,6 @@ class Solution:
return dfs(l, 0, True)
```
-### **Java**
-
```java
class Solution {
private int[] a = new int[12];
@@ -86,8 +84,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -124,8 +120,6 @@ public:
};
```
-### **Go**
-
```go
func numberOf2sInRange(n int) int {
a := make([]int, 12)
@@ -171,10 +165,6 @@ func numberOf2sInRange(n int) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.07.Baby Names/README.md b/lcci/17.07.Baby Names/README.md
index 28ee34bf85124..1c870de819bdd 100644
--- a/lcci/17.07.Baby Names/README.md
+++ b/lcci/17.07.Baby Names/README.md
@@ -22,9 +22,7 @@
## 解法
-
-
-**方法一:哈希表 + DFS**
+### 方法一:哈希表 + DFS
对于每个同义词对,我们将其两个名字建立双向边,存放在邻接表 $g$ 中,然后,我们遍历所有名字,将其存放在集合 $s$ 中,同时将其频率存放在哈希表 $cnt$ 中。
@@ -36,10 +34,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def trulyMostPopular(self, names: List[str], synonyms: List[str]) -> List[str]:
@@ -74,10 +68,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class Solution {
private Map> g = new HashMap<>();
@@ -127,8 +117,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -180,8 +168,6 @@ public:
};
```
-### **Go**
-
```go
func trulyMostPopular(names []string, synonyms []string) (ans []string) {
g := map[string][]string{}
@@ -228,8 +214,6 @@ func trulyMostPopular(names []string, synonyms []string) (ans []string) {
}
```
-### **TypeScript**
-
```ts
function trulyMostPopular(names: string[], synonyms: string[]): string[] {
const map = new Map();
@@ -261,10 +245,6 @@ function trulyMostPopular(names: string[], synonyms: string[]): string[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.07.Baby Names/README_EN.md b/lcci/17.07.Baby Names/README_EN.md
index 71f6d0769ff10..241c383278515 100644
--- a/lcci/17.07.Baby Names/README_EN.md
+++ b/lcci/17.07.Baby Names/README_EN.md
@@ -22,9 +22,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -60,8 +60,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class Solution {
private Map> g = new HashMap<>();
@@ -111,8 +109,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class Solution {
public:
@@ -164,8 +160,6 @@ public:
};
```
-### **Go**
-
```go
func trulyMostPopular(names []string, synonyms []string) (ans []string) {
g := map[string][]string{}
@@ -212,8 +206,6 @@ func trulyMostPopular(names []string, synonyms []string) (ans []string) {
}
```
-### **TypeScript**
-
```ts
function trulyMostPopular(names: string[], synonyms: string[]): string[] {
const map = new Map();
@@ -245,10 +237,6 @@ function trulyMostPopular(names: string[], synonyms: string[]): string[] {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.08.Circus Tower/README.md b/lcci/17.08.Circus Tower/README.md
index 3472bf66b4930..9af4baed0b041 100644
--- a/lcci/17.08.Circus Tower/README.md
+++ b/lcci/17.08.Circus Tower/README.md
@@ -18,9 +18,7 @@
## 解法
-
-
-**方法一:排序 + 离散化 + 树状数组**
+### 方法一:排序 + 离散化 + 树状数组
我们现将所有人按照身高从小到大排序,若身高相同,则按照体重从大到小排序。这样我们可以将问题转换为求体重数组的最长递增子序列的问题。
@@ -30,10 +28,6 @@
-### **Python3**
-
-
-
```python
class BinaryIndexedTree:
def __init__(self, n):
@@ -69,10 +63,6 @@ class Solution:
return ans
```
-### **Java**
-
-
-
```java
class BinaryIndexedTree {
private int n;
@@ -131,8 +121,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class BinaryIndexedTree {
public:
@@ -191,8 +179,6 @@ public:
};
```
-### **Go**
-
```go
type BinaryIndexedTree struct {
n int
@@ -253,10 +239,6 @@ func bestSeqAtIndex(height []int, weight []int) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.08.Circus Tower/README_EN.md b/lcci/17.08.Circus Tower/README_EN.md
index c0781fe4772c2..b894d3f5bed66 100644
--- a/lcci/17.08.Circus Tower/README_EN.md
+++ b/lcci/17.08.Circus Tower/README_EN.md
@@ -21,9 +21,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class BinaryIndexedTree:
@@ -60,8 +60,6 @@ class Solution:
return ans
```
-### **Java**
-
```java
class BinaryIndexedTree {
private int n;
@@ -120,8 +118,6 @@ class Solution {
}
```
-### **C++**
-
```cpp
class BinaryIndexedTree {
public:
@@ -180,8 +176,6 @@ public:
};
```
-### **Go**
-
```go
type BinaryIndexedTree struct {
n int
@@ -242,10 +236,6 @@ func bestSeqAtIndex(height []int, weight []int) int {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.09.Get Kth Magic Number/README.md b/lcci/17.09.Get Kth Magic Number/README.md
index b1eb11b498391..7d4fe3fea6a0c 100644
--- a/lcci/17.09.Get Kth Magic Number/README.md
+++ b/lcci/17.09.Get Kth Magic Number/README.md
@@ -15,32 +15,14 @@
## 解法
-
-
-**方法一:优先队列(小根堆)**
+### 方法一:优先队列(小根堆)
用一个小根堆维护当前最小的数,每次取出最小的数,然后乘以 $3$, $5$, $7$,分别加入堆中,直到取出第 $k$ 个数。
时间复杂度 $O(k\times \log k)$,空间复杂度 $O(k)$。
-**方法二:动态规划**
-
-方法一的做法足以通过本题,但如果在面试中,面试官可能要求我们实现一个复杂度更低的算法。因此,我们有必要掌握一种更优的算法。
-
-我们定义数组 $dp$,其中 $dp[i]$ 表示第 $i$ 个数,答案即为 $dp[k]$。
-
-定义三个指针 $p_3$, $p_5$, $p_7$,表示下一个数是当前指针指向的数乘以对应的质因数,初始值都为 $1$。
-
-当 $2\le i \le k$ 时,令 $dp[i] = \min(dp[p_3]\times 3, dp[p_5]\times 5, dp[p_7]\times 7)$,然后分别比较 $dp[i]$ 和 $dp[p_3]\times 3, dp[p_5]\times 5, dp[p_7]\times 7$,如果相等,则将对应的指针加 $1$。
-
-时间复杂度 $O(k)$,空间复杂度 $O(k)$。
-
-### **Python3**
-
-
-
```python
class Solution:
def getKthMagicNumber(self, k: int) -> int:
@@ -55,28 +37,6 @@ class Solution:
return h[0]
```
-```python
-class Solution:
- def getKthMagicNumber(self, k: int) -> int:
- dp = [1] * (k + 1)
- p3 = p5 = p7 = 1
- for i in range(2, k + 1):
- a, b, c = dp[p3] * 3, dp[p5] * 5, dp[p7] * 7
- v = min(a, b, c)
- dp[i] = v
- if v == a:
- p3 += 1
- if v == b:
- p5 += 1
- if v == c:
- p7 += 1
- return dp[k]
-```
-
-### **Java**
-
-
-
```java
class Solution {
private static final int[] FACTORS = new int[] {3, 5, 7};
@@ -102,33 +62,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int getKthMagicNumber(int k) {
- int[] dp = new int[k + 1];
- Arrays.fill(dp, 1);
- int p3 = 1, p5 = 1, p7 = 1;
- for (int i = 2; i <= k; ++i) {
- int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7;
- int v = Math.min(Math.min(a, b), c);
- dp[i] = v;
- if (v == a) {
- ++p3;
- }
- if (v == b) {
- ++p5;
- }
- if (v == c) {
- ++p7;
- }
- }
- return dp[k];
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -155,33 +88,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- int getKthMagicNumber(int k) {
- vector dp(k + 1, 1);
- int p3 = 1, p5 = 1, p7 = 1;
- for (int i = 2; i <= k; ++i) {
- int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7;
- int v = min(min(a, b), c);
- dp[i] = v;
- if (v == a) {
- ++p3;
- }
- if (v == b) {
- ++p5;
- }
- if (v == c) {
- ++p7;
- }
- }
- return dp[k];
- }
-};
-```
-
-### **Go**
-
```go
func getKthMagicNumber(k int) int {
q := hp{[]int{1}}
@@ -210,62 +116,6 @@ func (h *hp) Pop() any {
}
```
-```go
-func getKthMagicNumber(k int) int {
- dp := make([]int, k+1)
- dp[1] = 1
- p3, p5, p7 := 1, 1, 1
- for i := 2; i <= k; i++ {
- a, b, c := dp[p3]*3, dp[p5]*5, dp[p7]*7
- v := min(min(a, b), c)
- dp[i] = v
- if v == a {
- p3++
- }
- if v == b {
- p5++
- }
- if v == c {
- p7++
- }
- }
- return dp[k]
-}
-```
-
-### **C**
-
-```c
-#define min(a, b) (((a) < (b)) ? (a) : (b))
-
-int getKthMagicNumber(int k) {
- int* dp = (int*) malloc(sizeof(int) * k);
- dp[0] = 1;
- int index[3] = {0, 0, 0};
- for (int i = 1; i < k; i++) {
- int a = dp[index[0]] * 3;
- int b = dp[index[1]] * 5;
- int c = dp[index[2]] * 7;
- int num = min(a, min(b, c));
- dp[i] = num;
- if (a == num) {
- index[0]++;
- }
- if (b == num) {
- index[1]++;
- }
- if (c == num) {
- index[2]++;
- }
- }
- int res = dp[k - 1];
- free(dp);
- return res;
-}
-```
-
-### **TypeScript**
-
```ts
function getKthMagicNumber(k: number): number {
const dp = [1];
@@ -290,8 +140,6 @@ function getKthMagicNumber(k: number): number {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn get_kth_magic_number(k: i32) -> i32 {
@@ -319,10 +167,142 @@ impl Solution {
}
```
-### **...**
+```c
+#define min(a, b) (((a) < (b)) ? (a) : (b))
+
+int getKthMagicNumber(int k) {
+ int* dp = (int*) malloc(sizeof(int) * k);
+ dp[0] = 1;
+ int index[3] = {0, 0, 0};
+ for (int i = 1; i < k; i++) {
+ int a = dp[index[0]] * 3;
+ int b = dp[index[1]] * 5;
+ int c = dp[index[2]] * 7;
+ int num = min(a, min(b, c));
+ dp[i] = num;
+ if (a == num) {
+ index[0]++;
+ }
+ if (b == num) {
+ index[1]++;
+ }
+ if (c == num) {
+ index[2]++;
+ }
+ }
+ int res = dp[k - 1];
+ free(dp);
+ return res;
+}
+```
+
+
+
+### 方法二:动态规划
+
+方法一的做法足以通过本题,但如果在面试中,面试官可能要求我们实现一个复杂度更低的算法。因此,我们有必要掌握一种更优的算法。
+
+我们定义数组 $dp$,其中 $dp[i]$ 表示第 $i$ 个数,答案即为 $dp[k]$。
+
+定义三个指针 $p_3$, $p_5$, $p_7$,表示下一个数是当前指针指向的数乘以对应的质因数,初始值都为 $1$。
+
+当 $2\le i \le k$ 时,令 $dp[i] = \min(dp[p_3]\times 3, dp[p_5]\times 5, dp[p_7]\times 7)$,然后分别比较 $dp[i]$ 和 $dp[p_3]\times 3, dp[p_5]\times 5, dp[p_7]\times 7$,如果相等,则将对应的指针加 $1$。
+
+时间复杂度 $O(k)$,空间复杂度 $O(k)$。
+
+
+
+```python
+class Solution:
+ def getKthMagicNumber(self, k: int) -> int:
+ dp = [1] * (k + 1)
+ p3 = p5 = p7 = 1
+ for i in range(2, k + 1):
+ a, b, c = dp[p3] * 3, dp[p5] * 5, dp[p7] * 7
+ v = min(a, b, c)
+ dp[i] = v
+ if v == a:
+ p3 += 1
+ if v == b:
+ p5 += 1
+ if v == c:
+ p7 += 1
+ return dp[k]
+```
+
+```java
+class Solution {
+ public int getKthMagicNumber(int k) {
+ int[] dp = new int[k + 1];
+ Arrays.fill(dp, 1);
+ int p3 = 1, p5 = 1, p7 = 1;
+ for (int i = 2; i <= k; ++i) {
+ int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7;
+ int v = Math.min(Math.min(a, b), c);
+ dp[i] = v;
+ if (v == a) {
+ ++p3;
+ }
+ if (v == b) {
+ ++p5;
+ }
+ if (v == c) {
+ ++p7;
+ }
+ }
+ return dp[k];
+ }
+}
+```
+```cpp
+class Solution {
+public:
+ int getKthMagicNumber(int k) {
+ vector dp(k + 1, 1);
+ int p3 = 1, p5 = 1, p7 = 1;
+ for (int i = 2; i <= k; ++i) {
+ int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7;
+ int v = min(min(a, b), c);
+ dp[i] = v;
+ if (v == a) {
+ ++p3;
+ }
+ if (v == b) {
+ ++p5;
+ }
+ if (v == c) {
+ ++p7;
+ }
+ }
+ return dp[k];
+ }
+};
```
+```go
+func getKthMagicNumber(k int) int {
+ dp := make([]int, k+1)
+ dp[1] = 1
+ p3, p5, p7 := 1, 1, 1
+ for i := 2; i <= k; i++ {
+ a, b, c := dp[p3]*3, dp[p5]*5, dp[p7]*7
+ v := min(min(a, b), c)
+ dp[i] = v
+ if v == a {
+ p3++
+ }
+ if v == b {
+ p5++
+ }
+ if v == c {
+ p7++
+ }
+ }
+ return dp[k]
+}
```
+
+
diff --git a/lcci/17.09.Get Kth Magic Number/README_EN.md b/lcci/17.09.Get Kth Magic Number/README_EN.md
index 5a0f071063d55..d87bedd1fc828 100644
--- a/lcci/17.09.Get Kth Magic Number/README_EN.md
+++ b/lcci/17.09.Get Kth Magic Number/README_EN.md
@@ -14,9 +14,9 @@
## Solutions
-
+### Solution 1
-### **Python3**
+
```python
class Solution:
@@ -32,26 +32,6 @@ class Solution:
return h[0]
```
-```python
-class Solution:
- def getKthMagicNumber(self, k: int) -> int:
- dp = [1] * (k + 1)
- p3 = p5 = p7 = 1
- for i in range(2, k + 1):
- a, b, c = dp[p3] * 3, dp[p5] * 5, dp[p7] * 7
- v = min(a, b, c)
- dp[i] = v
- if v == a:
- p3 += 1
- if v == b:
- p5 += 1
- if v == c:
- p7 += 1
- return dp[k]
-```
-
-### **Java**
-
```java
class Solution {
private static final int[] FACTORS = new int[] {3, 5, 7};
@@ -77,33 +57,6 @@ class Solution {
}
```
-```java
-class Solution {
- public int getKthMagicNumber(int k) {
- int[] dp = new int[k + 1];
- Arrays.fill(dp, 1);
- int p3 = 1, p5 = 1, p7 = 1;
- for (int i = 2; i <= k; ++i) {
- int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7;
- int v = Math.min(Math.min(a, b), c);
- dp[i] = v;
- if (v == a) {
- ++p3;
- }
- if (v == b) {
- ++p5;
- }
- if (v == c) {
- ++p7;
- }
- }
- return dp[k];
- }
-}
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -130,33 +83,6 @@ public:
};
```
-```cpp
-class Solution {
-public:
- int getKthMagicNumber(int k) {
- vector dp(k + 1, 1);
- int p3 = 1, p5 = 1, p7 = 1;
- for (int i = 2; i <= k; ++i) {
- int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7;
- int v = min(min(a, b), c);
- dp[i] = v;
- if (v == a) {
- ++p3;
- }
- if (v == b) {
- ++p5;
- }
- if (v == c) {
- ++p7;
- }
- }
- return dp[k];
- }
-};
-```
-
-### **Go**
-
```go
func getKthMagicNumber(k int) int {
q := hp{[]int{1}}
@@ -185,62 +111,6 @@ func (h *hp) Pop() any {
}
```
-```go
-func getKthMagicNumber(k int) int {
- dp := make([]int, k+1)
- dp[1] = 1
- p3, p5, p7 := 1, 1, 1
- for i := 2; i <= k; i++ {
- a, b, c := dp[p3]*3, dp[p5]*5, dp[p7]*7
- v := min(min(a, b), c)
- dp[i] = v
- if v == a {
- p3++
- }
- if v == b {
- p5++
- }
- if v == c {
- p7++
- }
- }
- return dp[k]
-}
-```
-
-### **C**
-
-```c
-#define min(a, b) (((a) < (b)) ? (a) : (b))
-
-int getKthMagicNumber(int k) {
- int* dp = (int*) malloc(sizeof(int) * k);
- dp[0] = 1;
- int index[3] = {0, 0, 0};
- for (int i = 1; i < k; i++) {
- int a = dp[index[0]] * 3;
- int b = dp[index[1]] * 5;
- int c = dp[index[2]] * 7;
- int num = min(a, min(b, c));
- dp[i] = num;
- if (a == num) {
- index[0]++;
- }
- if (b == num) {
- index[1]++;
- }
- if (c == num) {
- index[2]++;
- }
- }
- int res = dp[k - 1];
- free(dp);
- return res;
-}
-```
-
-### **TypeScript**
-
```ts
function getKthMagicNumber(k: number): number {
const dp = [1];
@@ -265,8 +135,6 @@ function getKthMagicNumber(k: number): number {
}
```
-### **Rust**
-
```rust
impl Solution {
pub fn get_kth_magic_number(k: i32) -> i32 {
@@ -294,10 +162,132 @@ impl Solution {
}
```
-### **...**
+```c
+#define min(a, b) (((a) < (b)) ? (a) : (b))
+
+int getKthMagicNumber(int k) {
+ int* dp = (int*) malloc(sizeof(int) * k);
+ dp[0] = 1;
+ int index[3] = {0, 0, 0};
+ for (int i = 1; i < k; i++) {
+ int a = dp[index[0]] * 3;
+ int b = dp[index[1]] * 5;
+ int c = dp[index[2]] * 7;
+ int num = min(a, min(b, c));
+ dp[i] = num;
+ if (a == num) {
+ index[0]++;
+ }
+ if (b == num) {
+ index[1]++;
+ }
+ if (c == num) {
+ index[2]++;
+ }
+ }
+ int res = dp[k - 1];
+ free(dp);
+ return res;
+}
+```
+
+
+
+### Solution 2
+
+
+
+```python
+class Solution:
+ def getKthMagicNumber(self, k: int) -> int:
+ dp = [1] * (k + 1)
+ p3 = p5 = p7 = 1
+ for i in range(2, k + 1):
+ a, b, c = dp[p3] * 3, dp[p5] * 5, dp[p7] * 7
+ v = min(a, b, c)
+ dp[i] = v
+ if v == a:
+ p3 += 1
+ if v == b:
+ p5 += 1
+ if v == c:
+ p7 += 1
+ return dp[k]
+```
+
+```java
+class Solution {
+ public int getKthMagicNumber(int k) {
+ int[] dp = new int[k + 1];
+ Arrays.fill(dp, 1);
+ int p3 = 1, p5 = 1, p7 = 1;
+ for (int i = 2; i <= k; ++i) {
+ int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7;
+ int v = Math.min(Math.min(a, b), c);
+ dp[i] = v;
+ if (v == a) {
+ ++p3;
+ }
+ if (v == b) {
+ ++p5;
+ }
+ if (v == c) {
+ ++p7;
+ }
+ }
+ return dp[k];
+ }
+}
+```
+```cpp
+class Solution {
+public:
+ int getKthMagicNumber(int k) {
+ vector dp(k + 1, 1);
+ int p3 = 1, p5 = 1, p7 = 1;
+ for (int i = 2; i <= k; ++i) {
+ int a = dp[p3] * 3, b = dp[p5] * 5, c = dp[p7] * 7;
+ int v = min(min(a, b), c);
+ dp[i] = v;
+ if (v == a) {
+ ++p3;
+ }
+ if (v == b) {
+ ++p5;
+ }
+ if (v == c) {
+ ++p7;
+ }
+ }
+ return dp[k];
+ }
+};
```
+```go
+func getKthMagicNumber(k int) int {
+ dp := make([]int, k+1)
+ dp[1] = 1
+ p3, p5, p7 := 1, 1, 1
+ for i := 2; i <= k; i++ {
+ a, b, c := dp[p3]*3, dp[p5]*5, dp[p7]*7
+ v := min(min(a, b), c)
+ dp[i] = v
+ if v == a {
+ p3++
+ }
+ if v == b {
+ p5++
+ }
+ if v == c {
+ p7++
+ }
+ }
+ return dp[k]
+}
```
+
+
diff --git a/lcci/17.10.Find Majority Element/README.md b/lcci/17.10.Find Majority Element/README.md
index 7440f16a9c00b..a7516dcf653e1 100644
--- a/lcci/17.10.Find Majority Element/README.md
+++ b/lcci/17.10.Find Majority Element/README.md
@@ -33,9 +33,7 @@
## 解法
-
-
-**方法一:摩尔投票法**
+### 方法一:摩尔投票法
摩尔投票法的基本步骤如下:
@@ -51,10 +49,6 @@
-### **Python3**
-
-
-
```python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
@@ -67,10 +61,6 @@ class Solution:
return m if nums.count(m) > len(nums) // 2 else -1
```
-### **Java**
-
-
-
```java
class Solution {
public int majorityElement(int[] nums) {
@@ -94,36 +84,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var majorityElement = function (nums) {
- let cnt = 0,
- m = 0;
- for (const v of nums) {
- if (cnt == 0) {
- m = v;
- cnt = 1;
- } else {
- cnt += m == v ? 1 : -1;
- }
- }
- cnt = 0;
- for (const v of nums) {
- if (m == v) {
- ++cnt;
- }
- }
- return cnt > nums.length / 2 ? m : -1;
-};
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -142,8 +102,6 @@ public:
};
```
-### **Go**
-
```go
func majorityElement(nums []int) int {
cnt, m := 0, 0
@@ -171,7 +129,31 @@ func majorityElement(nums []int) int {
}
```
-### **C#**
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var majorityElement = function (nums) {
+ let cnt = 0,
+ m = 0;
+ for (const v of nums) {
+ if (cnt == 0) {
+ m = v;
+ cnt = 1;
+ } else {
+ cnt += m == v ? 1 : -1;
+ }
+ }
+ cnt = 0;
+ for (const v of nums) {
+ if (m == v) {
+ ++cnt;
+ }
+ }
+ return cnt > nums.length / 2 ? m : -1;
+};
+```
```cs
public class Solution {
@@ -202,10 +184,6 @@ public class Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.10.Find Majority Element/README_EN.md b/lcci/17.10.Find Majority Element/README_EN.md
index 7e914dc9e821f..0b853402f0b4f 100644
--- a/lcci/17.10.Find Majority Element/README_EN.md
+++ b/lcci/17.10.Find Majority Element/README_EN.md
@@ -38,12 +38,10 @@
## Solutions
-Boyer–Moore majority vote algorithm
+### Solution 1
-### **Python3**
-
```python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
@@ -56,8 +54,6 @@ class Solution:
return m if nums.count(m) > len(nums) // 2 else -1
```
-### **Java**
-
```java
class Solution {
public int majorityElement(int[] nums) {
@@ -81,36 +77,6 @@ class Solution {
}
```
-### **JavaScript**
-
-```js
-/**
- * @param {number[]} nums
- * @return {number}
- */
-var majorityElement = function (nums) {
- let cnt = 0,
- m = 0;
- for (const v of nums) {
- if (cnt == 0) {
- m = v;
- cnt = 1;
- } else {
- cnt += m == v ? 1 : -1;
- }
- }
- cnt = 0;
- for (const v of nums) {
- if (m == v) {
- ++cnt;
- }
- }
- return cnt > nums.length / 2 ? m : -1;
-};
-```
-
-### **C++**
-
```cpp
class Solution {
public:
@@ -129,8 +95,6 @@ public:
};
```
-### **Go**
-
```go
func majorityElement(nums []int) int {
cnt, m := 0, 0
@@ -158,7 +122,31 @@ func majorityElement(nums []int) int {
}
```
-### **C#**
+```js
+/**
+ * @param {number[]} nums
+ * @return {number}
+ */
+var majorityElement = function (nums) {
+ let cnt = 0,
+ m = 0;
+ for (const v of nums) {
+ if (cnt == 0) {
+ m = v;
+ cnt = 1;
+ } else {
+ cnt += m == v ? 1 : -1;
+ }
+ }
+ cnt = 0;
+ for (const v of nums) {
+ if (m == v) {
+ ++cnt;
+ }
+ }
+ return cnt > nums.length / 2 ? m : -1;
+};
+```
```cs
public class Solution {
@@ -189,10 +177,6 @@ public class Solution {
}
```
-### **...**
-
-```
-
-```
-
+
+
diff --git a/lcci/17.11.Find Closest/README.md b/lcci/17.11.Find Closest/README.md
index bd41b102d575e..bb4eca1047891 100644
--- a/lcci/17.11.Find Closest/README.md
+++ b/lcci/17.11.Find Closest/README.md
@@ -20,14 +20,10 @@
## 解法
-
+### 方法一
-### **Python3**
-
-
-
```python
class Solution:
def findClosest(self, words: List[str], word1: str, word2: str) -> int:
@@ -41,28 +37,6 @@ class Solution:
return ans
```
-```python
-class Solution:
- def findClosest(self, words: List[str], word1: str, word2: str) -> int:
- d = defaultdict(list)
- for i, w in enumerate(words):
- d[w].append(i)
- ans = 1e5
- idx1, idx2 = d[word1], d[word2]
- i, j, m, n = 0, 0, len(idx1), len(idx2)
- while i < m and j < n:
- ans = min(ans, abs(idx1[i] - idx2[j]))
- if idx1[i] < idx2[j]:
- i += 1
- else:
- j += 1
- return ans
-```
-
-### **Java**
-
-
-
```java
class Solution {
public int findClosest(String[] words, String word1, String word2) {
@@ -81,31 +55,45 @@ class Solution {
}
```
-```java
+```cpp
class Solution {
- public int findClosest(String[] words, String word1, String word2) {
- Map> d = new HashMap<>();
- for (int i = 0; i < words.length; ++i) {
- d.computeIfAbsent(words[i], k -> new ArrayList<>()).add(i);
- }
- List idx1 = d.get(word1), idx2 = d.get(word2);
- int i = 0, j = 0, m = idx1.size(), n = idx2.size();
- int ans = 100000;
- while (i < m && j < n) {
- int t = Math.abs(idx1.get(i) - idx2.get(j));
- ans = Math.min(ans, t);
- if (idx1.get(i) < idx2.get(j)) {
- ++i;
- } else {
- ++j;
- }
+public:
+ int findClosest(vector& words, string word1, string word2) {
+ int i = 1e5, j = -1e5, ans = 1e5;
+ for (int k = 0; k < words.size(); ++k) {
+ string word = words[k];
+ if (word == word1)
+ i = k;
+ else if (word == word2)
+ j = k;
+ ans = min(ans, abs(i - j));
}
return ans;
}
-}
+};
```
-### **TypeScript**
+```go
+func findClosest(words []string, word1 string, word2 string) int {
+ i, j, ans := 100000, -100000, 100000
+ for k, word := range words {
+ if word == word1 {
+ i = k
+ } else if word == word2 {
+ j = k
+ }
+ ans = min(ans, abs(i-j))
+ }
+ return ans
+}
+
+func abs(x int) int {
+ if x < 0 {
+ return -x
+ }
+ return x
+}
+```
```ts
function findClosest(words: string[], word1: string, word2: string): number {
@@ -126,24 +114,74 @@ function findClosest(words: string[], word1: string, word2: string): number {
}
```
-### **C++**
+```rust
+impl Solution {
+ pub fn find_closest(words: Vec, word1: String, word2: String) -> i32 {
+ let mut res = i32::MAX;
+ let mut index1 = -1;
+ let mut index2 = -1;
+ for (i, word) in words.iter().enumerate() {
+ let i = i as i32;
+ if word.eq(&word1) {
+ index1 = i;
+ } else if word.eq(&word2) {
+ index2 = i;
+ }
+ if index1 != -1 && index2 != -1 {
+ res = res.min((index1 - index2).abs());
+ }
+ }
+ res
+ }
+}
+```
+
+
-```cpp
+### 方法二
+
+
+
+```python
+class Solution:
+ def findClosest(self, words: List[str], word1: str, word2: str) -> int:
+ d = defaultdict(list)
+ for i, w in enumerate(words):
+ d[w].append(i)
+ ans = 1e5
+ idx1, idx2 = d[word1], d[word2]
+ i, j, m, n = 0, 0, len(idx1), len(idx2)
+ while i < m and j < n:
+ ans = min(ans, abs(idx1[i] - idx2[j]))
+ if idx1[i] < idx2[j]:
+ i += 1
+ else:
+ j += 1
+ return ans
+```
+
+```java
class Solution {
-public:
- int findClosest(vector& words, string word1, string word2) {
- int i = 1e5, j = -1e5, ans = 1e5;
- for (int k = 0; k < words.size(); ++k) {
- string word = words[k];
- if (word == word1)
- i = k;
- else if (word == word2)
- j = k;
- ans = min(ans, abs(i - j));
+ public int findClosest(String[] words, String word1, String word2) {
+ Map> d = new HashMap<>();
+ for (int i = 0; i < words.length; ++i) {
+ d.computeIfAbsent(words[i], k -> new ArrayList<>()).add(i);
+ }
+ List idx1 = d.get(word1), idx2 = d.get(word2);
+ int i = 0, j = 0, m = idx1.size(), n = idx2.size();
+ int ans = 100000;
+ while (i < m && j < n) {
+ int t = Math.abs(idx1.get(i) - idx2.get(j));
+ ans = Math.min(ans, t);
+ if (idx1.get(i) < idx2.get(j)) {
+ ++i;
+ } else {
+ ++j;
+ }
}
return ans;
}
-};
+}
```
```cpp
@@ -168,30 +206,6 @@ public:
};
```
-### **Go**
-
-```go
-func findClosest(words []string, word1 string, word2 string) int {
- i, j, ans := 100000, -100000, 100000
- for k, word := range words {
- if word == word1 {
- i = k
- } else if word == word2 {
- j = k
- }
- ans = min(ans, abs(i-j))
- }
- return ans
-}
-
-func abs(x int) int {
- if x < 0 {
- return -x
- }
- return x
-}
-```
-
```go
func findClosest(words []string, word1 string, word2 string) int {
d := map[string][]int{}
@@ -223,34 +237,6 @@ func abs(x int) int {
}
```
-### **Rust**
-
-```rust
-impl Solution {
- pub fn find_closest(words: Vec